我有两个表:评论和喜欢。
public class Comment {
CommentID { get; set; }
....
}
public class Like {
CommentID { get; set; }
UserID { get; set; }
}
首先使用实体框架核心 2.0 代码,我想将我的“Like”模型定义为仅具有引用其他主键(作为外键)的两个字段,但我还希望值的组合为主键表的。任何帮助将不胜感激!
最佳答案
所以,这是这里发生的事情:
1) 有两个类:Comment
和User
。
2) 第三个类,Like
,包含对对应于数据库中外键的两个类的引用(导航属性):UserId
和 CommentId
。我明确使用了 ForeignKey
属性,这样您就可以清楚 EF 将使用哪些属性作为外键。在这种特殊情况下,您可以省略此属性,因为 EF 会自动计算出来(因为两个类中的名称都匹配)。请注意,外键不是强制性的,但它们有优势。
3) UserId
和CommentId
组成复合键。 Column
属性配置数据库中列的顺序(所谓的序号)。这对 EF 很重要。
4) User
和 Comment
类也有导航属性(因为它是 one-to-many< 的
关系):one
端喜欢
。
5) 最后,总是
使用Table
属性来避免复数问题,因为there's no way将其关闭。
[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 中设置组合键
用于指定复合主键的 Key
(和 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 中配置复合键,您需要使用 anonymous type .同样,属性的顺序很重要。
关于c# - 2 外键作为主键使用 EF Core 2.0 Code First,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50398457/