Kulkejszyn
Kulkejszyn

Reputation: 65

EF Core Multiple one to many relationship

I am building simple application using entity framework to create realations which should looks like.

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 and Tags are empty classes, only with index.

How to create a correct relationship between user User class and Post?

This is what i ended up with in 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);
        });

Which gives me error that relationship already exists. I want sql to create separate tables to group liked and owned posts.

Thank you for your help.

Upvotes: 0

Views: 1198

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89386

I presume two ApplictionUsers can like the same Post, so something like this:

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

Upvotes: 1

Related Questions