c# - 2 外键作为主键使用 EF Core 2.0 Code First

标签 c# entity-framework-core

我有两个表:评论喜欢

public class Comment {
  CommentID { get; set; }
  ....
}

public class Like {
  CommentID { get; set; }
  UserID { get; set; }
}

首先使用实体​​框架核心 2.0 代码,我想将我的“Like”模型定义为仅具有引用其他主键(作为外键)的两个字段,但我还希望值的组合为主键表的。任何帮助将不胜感激!

最佳答案

所以,这是这里发生的事情:

1) 有两个类:CommentUser

2) 第三个类,Like,包含对对应于数据库中外键的两个类的引用(导航属性):UserIdCommentId 。我明确使用了 ForeignKey 属性,这样您就可以清楚 EF 将使用哪些属性作为外键。在这种特殊情况下,您可以省略此属性,因为 EF 会自动计算出来(因为两个类中的名称都匹配)。请注意,外键不是强制性的,但它们有优势。

3) UserIdCommentId 组成复合键。 Column 属性配置数据库中列的顺序(所谓的序号)。这对 EF 很重要。

4) UserComment 类也有导航属性(因为它是 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/

相关文章:

c# - Unity 5 中的 GUIText(需要替代方案)

c# - 如何将枚举值设置为 Web 用户控件的自定义属性?

c# - .NET Form Treeview 节点宽度和自定义绘制文本(无法设置节点边界)

EF Core 3.0 中的 LINQ 重大更改。使用表达式

postgresql - 使用 EF Core 5 查询 Postgres Json 字段

c# - GroupBy 和 Count by condition Entity Framework

c# - "Merging"类型,不使用反射或重复代码?

c# - 将 <T>(T obj) 与 Linq 查询结合使用

c# - 使用 EF Core Include 连接 ExpressionVisitor

c# - 在 Entity Framework Core 中获取导航属性