How to associate one table to many parents using EF Code First

时光毁灭记忆、已成空白 提交于 2019-12-05 20:37:34

If you create a many-to-many relationship between notes and all entities that can have notes, you will have a junction table for each owning type and a nice and clean note table. The simplest way to create the many-to-many relationships is to override the DbContext.OnModelCreating method.

Your DbContext:

  public class MyDatabase : DbContext
  {
    // Protected methods

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      base.OnModelCreating(modelBuilder);

      modelBuilder.Entity<Customer>().HasMany(x => x.Notes).WithMany();
      modelBuilder.Entity<Order>().HasMany(x => x.Notes).WithMany();
    }

    public MyDatabase() : base("MyDatabase")
    {
    }

    // Properties

    public DbSet<Customer> Customers { get; set; }

    public DbSet<Order> Orders { get; set; }

    public DbSet<Note> Notes { get; set; }
  }

This will produce the following tables: Customer, Orders, Notes, CustomerNotes and OrderNotes with the last two being junction tables with only two columns each.

NOTE! With this solution it is also possible for entities to share notes, e.g. a Customer and an Order can own the same Note.

Not sure if fits but you could use EF hierarchies to do it. See This article:

http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx

Basically you could have three types for your notes all inheriting from a basic note type.

There are three types of hierarchies in EF so its a three partes article...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!