【问题标题】:EF Core Multiple one to many relationshipEF Core 多对多关系
【发布时间】: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 创建单独的表来对喜欢和拥有的帖子进行分组。

感谢您的帮助。

【问题讨论】:

标签: c# entity-framework .net-core relationship


【解决方案1】:

我假设两个 ApplictionUser 可以喜欢同一个帖子,所以是这样的:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Post>()
        .HasOne(p => p.Owner)
        .WithMany(u => u.UserPost)
        .OnDelete(DeleteBehavior.Restrict);

    modelBuilder.Entity<ApplicationUser>()
        .HasMany(u => u.LikedPosts)
        .WithMany(p => p.Likers);
        

    base.OnModelCreating(modelBuilder);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-02
    • 2019-01-19
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 2021-03-30
    • 2017-09-08
    • 1970-01-01
    相关资源
    最近更新 更多