Mapping entity framework model to multiple tables

12,945

Solution 1

I have not implemented this but a quick search provides many good examples of a practice known as Entity Splitting. The following should be useful:

http://www.c-sharpcorner.com/UploadFile/ff2f08/entity-splitting-in-entity-framework-6-code-first-approach/

public partial class Employee  
{  
   // These fields come from the “Employee” table  
   public int EmployeeId { get; set; }   
   public string Code { get; set; }  
   public string Name { get; set; }  

   // These fields come from the “EmployeeDetails” table  
   public string PhoneNumber { get; set; }  
   public string EmailAddress { get; set; }  
} 

public partial class Model : DbContext  
{  
   public Model() : base("name=EntityModel")  
   {  
      Database.Log = Console.WriteLine;  
   }  
   public virtual DbSet<Employee> Employees { get; set; }  

   protected override void OnModelCreating(DbModelBuilder modelBuilder)  
   {  
      modelBuilder.Entity<Employee>()  
      .Map(map =>  
      {  
          map.Properties(p => new  
          {  
             p.EmployeeId,  
             p.Name,  
             p.Code  
          });  
          map.ToTable("Employee");  
      })  
      // Map to the Users table  
      .Map(map =>  
      {  
          map.Properties(p => new  
          {  
             p.PhoneNumber,  
             p.EmailAddress  
          });  
          map.ToTable("EmployeeDetails");  
      });  
   }  
}

All credit for the above code goes to linked post

Solution 2

In this case you can use IModelCacheKeyFactory, which allow to hook into the model caching mechanism so EF is able to create different models based on its property.

This article explains how

Share:
12,945

Related videos on Youtube

Sasi
Author by

Sasi

I'm a full-stack .Net and Angular web application developer. Having a good experience with various Azure services.

Updated on June 04, 2022

Comments

  • Sasi
    Sasi almost 2 years

    How can I map an entity framework model to multiple tables? How to perform insertion operation to specific table (by reference of string which stores the table name)?

  • Sasi
    Sasi almost 8 years
    Here we are mapping one entity to two different tables. But I need to make the table mapping dynamically. For example, Database contains schools details from different states. Details from each state should go to the particular state table. Here entity properties are same, but every time we may have to map different tables.
  • benjamingranados
    benjamingranados over 3 years
    I know this has some time; but for others to know, maybe you have to use IModelCacheKeyFactory. Here's an article that uses dynamic tables: medium.com/@yanxiaodi/…
  • Karthic G
    Karthic G over 3 years
    What is the equivalent of Map() in EF Core