【发布时间】:2021-10-11 06:32:59
【问题描述】:
我正在使用实体框架构建简单的应用程序来创建应该看起来像这样的现实。
public class Post
{
public long Id { get; set; }
public string Title;
public ICollection<Comment> Comments { get; set; } = new List<Comment>();
public ApplicationUser Owner { get; set; }
public ICollection<Tag> Tags { get; set; } = new List<Tag>();
public int LikesCount { get; set; }
}
public class ApplicationUser: IdentityUser
{
public ICollection<Post> UserPost { get; set; } = new List<Post>();
public ICollection<Post> LikedPosts { get; set; } = new List<Post>();
}
public class Comment : Auditable
{
public long Id { get; set; }
public string Content { get; set; }
}
public class Tag
{
public long Id { get; set; }
public string TagString { get; set; }
}
Comment 和 Tags 是空类,只有索引。
如何在用户User class和Post之间建立正确的关系?
这就是我在 fluent api 中得到的结果:
builder.Entity<Post>(post =>
{
post.HasKey(p => p.Id);
post.HasOne(p => p.Owner)
.WithMany(u => u.LikedPosts)
.HasForeignKey(p => p.Id)
.OnDelete(DeleteBehavior.Cascade);
post.HasOne(p => p.Owner)
.WithMany(u => u.UserPost)
.HasForeignKey(p => p.Id)
.OnDelete(DeleteBehavior.Cascade);
});
这给了我关系已经存在的错误。 我希望 sql 创建单独的表来对喜欢和拥有的帖子进行分组。
感谢您的帮助。
【问题讨论】:
-
相关:Defining multiple Foreign Key for the Same table in Entity Framework Code First。
post.HasOne(p => p.Liker)在第一次恋爱中有帮助吗?
标签: c# entity-framework .net-core relationship