问题描述
我有两个表:评论和赞。
。4) The User and Comment classes also have navigation properties (since it's one side of one-to-many relations): Likes.
5)最后,总是使用 Table 属性可避免出现复数问题,因为将其关闭。
5) Finally, always use Table attribute to avoid problems with pluralizations because there's no way to turn it off.
[Table("Comment")] public class Comment { public int CommentID { get; set; } public List<Like> Likes { get; set; } } [Table("User")] public class User { public int UserId { get; set; } public List<Like> Likes { get; set; } } [Table("Like")] public class Like { [Key] [Column(Order = 1)] public int CommentID { get; set; } [Key] [Column(Order = 2)] public int UserID { get; set; } [ForeignKey("CommentId")] public Comment Comment { get; set; } [ForeignKey("UserId")] public User User { get; set; } }更新
在EF Core中设置复合键
键(和 Column )属性(用于指定复合主键)实际上在EF Core中不起作用-它们在EF6中起作用。要在EF Core中配置组合键,您需要使用Fluent Configuration。
The Key (and Column) attributes, used to designate composite primary key, actually, don't work in EF Core - they work in EF6. To configure composite key in EF Core, you need to use Fluent Configuration.
您有两种选择。
选项1。在 OnModelCreatingMethod 中进行所有配置:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Like>().HasKey(l => new { l.CommentID, l.UserID }); }选项2。将所有配置移到单独的位置类并将其应用于 OnModelCreating :
OPTION 2. Move all the configuration into separate class and apply it in OnModelCreating:
1)创建用于配置的单独类
1) Create separate class for configuration
class LikeConfiguration : IEntityTypeConfiguration<Like> { public void Configure(EntityTypeBuilder<Like> builder) { builder.HasKey(l => new { l.CommentID, l.UserID }); } }2)应用配置:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new LikeConfiguration()); }选择任何您喜欢的选项。
Choose any option you like.
如您所见,要在Fluent Configuration中配置组合键,您需要使用。同样,属性的顺序很重要。
As you see, to configure composite key in Fluent Configuration, you need to use anonymous type. And again, the order of properties matters.
这篇关于首先使用EF Core 2.0代码将2个外键作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!