Question

I have a LinkTable named: BlogsBlogPosts that relates two other tables named: Blogs and BlogPosts together, I want the link table to appear in the list of entities and There will be two one to many relationships defined on the linktable am I correct to define it like this?:

public class BlogsBlogPostConfiguration : EntityTypeConfiguration<BlogsBlogPost>
{
    public BlogsBlogPostConfiguration()
    {
        this.HasRequired(bb => bb.Blog)
        .WithMany(b => b.BlogsBlogPosts)
        .HasForeignKey(bb =>bb.BlogID);

        this.HasRequired(bb => bb.BlogPost)
       .WithMany(bp => bp.BlogsBlogPosts)
       .HasForeignKey(bb => bb.BlogPostID);
    }
}
Was it helpful?

Solution

Yes. The only question which remains for me is: What about the primary key property of BlogsBlogPost? Two options:

  • You either have a distinct key property like public int BlogsBlogPostID { get; set; } or public int ID { get; set; } in this entity. In this case combinations of (BlogID, BlogPostID) don't have to be unique.

  • Or you have a composite key consisting of (BlogID, BlogPostID). You would have to mark this with the [Key] annotation or define it in Fluent API:

    this.HasKey(bbp => new { bbp.BlogID, bbp.BlogPostID });
    

    Now combinations of (BlogID, BlogPostID) must be unique. This is more of a "many-to-many relationship with additional data in the link table" type of relationship.

Both models are possible. Which to use depends on your business needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top