[英]EF Core join table for one-to-many relationship
我有以下类:User、Post 和 UserPost。 User 和 Post 是一对多的关系。 还有一个名为 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
}
在我的数据库上下文 class 中,我定义了这样的用户/帖子关系:
builder.Entity<User>()
.HasMany(u => u.Posts)
.WithOne(p => p.User)
现在我想定义 UserPost model 的关系,但不知道如何 go 关于它。 到目前为止,我有:
builder.Entity<UserPost>()
.HasKey(x => new { x.UserId, x.PostId })
还需要什么吗?
写下你的整个关系如下:
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 UserVote
:
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);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.