所以,这是这里发生的事情:
1)有两个类:Comment
and User
.
2)第三节课,Like
,保存对与数据库中的外键相对应的两个类的引用(导航属性):UserId
and CommentId
。我明确使用了ForeignKey
属性,以便您清楚 EF 将使用哪些属性作为外键。在这种特殊情况下,您可以省略此属性,因为 EF 会自动计算出它(因为两个类中的名称都匹配)。请注意,拥有外键不是强制性的,但它们有优点。
3) The UserId
and CommentId
包括复合键。这Column
属性配置数据库中列的顺序(所谓的序数)。这对于 EF 来说很重要。
4) The User
and Comment
类也有导航属性(因为它是one
侧one-to-many
关系):Likes
.
5)最后,always
use Table
属性以避免复数问题,因为不可能 https://stackoverflow.com/questions/37493095/entity-framework-core-rc2-table-name-pluralization将其关闭。
[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; }
}
UPDATE
在 EF Core 中设置复合键
The Key
(and Column
) 属性,用于指定复合主键,实际上在 EF Core 中不起作用 - 它们在 EF6 中起作用。要在 EF Core 中配置复合键,需要使用 Fluent Configuration。
您有两种选择。
选项1。进行所有配置OnModelCreatingMethod
:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Like>().HasKey(l => new { l.CommentID, l.UserID });
}
选项 2。将所有配置移至单独的类中并将其应用到OnModelCreating
:
1)创建单独的类进行配置
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());
}
选择您喜欢的任何选项。
如您所见,要在 Fluent Configuration 中配置复合键,您需要使用匿名类型 https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types。再说一遍,属性的顺序很重要。