一对多关系的EF Core连接表

时间:2020-06-05 05:53:40

标签: entity-framework .net-core entity-framework-core

我有以下课程:User,Post和UserPost。用户和帖子具有一对多关系。还有一个名为UserPost的第三个联接表,该表跟踪每个帖子获得的上/下投票。为了确保每个用户只能进行一次投票/降级投票,该表的ID(PK)是User和Post ID的组合键。

public class User {
    public Guid Id {get; set;}
    public string UserName {get; set;}
    public ICollection<Post> Posts {get; set;}
}

public class Post {
    public Guid Id {get; set;}
    public string Content {get;set;}
    public User User {get; set;}
}

public UserPost {
    public Guid Id {get; set;} // This should be a composite key of User ID and Post ID
    public Guid PostId {get;set;}
    public Guid UserId {get;set;}
    public VoteType VoteType {get;  set;}
}

public enum VoteType {
    Up = 1,
    Down = 0
}

在我的数据库上下文类中,我定义了用户/帖子关系,如下所示:

builder.Entity<User>()
    .HasMany(u => u.Posts)
    .WithOne(p => p.User)

现在,我想为UserPost模型定义关系,但不确定如何处理。到目前为止,我有:

builder.Entity<UserPost>()
   .HasKey(x => new { x.UserId, x.PostId })

还需要什么吗?

1 个答案:

答案 0 :(得分:0)

编写您的整个关系,如下所示:

public class User 
{
    public Guid Id {get; set;}
    public string UserName {get; set;}
    public ICollection<Post> Posts {get; set;}
}

public class Post 
{
    public Guid Id {get; set;}
    public string Content {get;set;}

    public Guid UserId {get; set;}
    public User User {get; set;}
}

public UserVote // Rename this from UserPost to UserVote to keep naming consistency. 
{
    public Guid PostId {get;set;}
    public Guid UserId {get;set;}
    public VoteType VoteType {get;  set;}

    public Post Post {get; set;}
    public User User {get; set;}
}

public enum VoteType {
    Up = 1,
    Down = 0
}
现在,UserVote

Fluent API 配置如下:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);

   modelBuilder.Entity<UserVote>(e =>
   { 
       e.HasKey(uv => new { uv.PostId, uv.UserId}); //<-- Here is the composite key.
       e.HasOne(uv => uv.Post).WithMany().HasForeignKey(uv => uv.PostId).OnDelete(DeleteBehavior.Restrict);
       e.HasOne(uv => uv.User).WithMany().HasForeignKey(uv => uv.UserId).OnDelete(DeleteBehavior.Restrict);
   });
}