简体   繁体   中英

EF Core join table for one-to-many relationship

I have the following classes: User, Post and UserPost. User and Post have a 1-to-many relationship. There's a third join table called UserPost that tracks the up/down vote each post gets. To ensure each user can only upvote/downvote once, the ID (PK) of this table is a composite key of User and 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
}

In my DB Context class I defined the User/Post relationship like this:

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

Now I want to define the relationship for the UserPost model but not sure how to go about it. So far I have:

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

Does it require anything further?

Write your whole relationship as follows:

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
}

Now, Fluent API configuration for the UserVote as follows:

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);
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM