[英]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.