0

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.

1

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.