Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping entity framework model to multiple tables

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)?

like image 209
Sasi Avatar asked Jul 15 '16 06:07

Sasi


People also ask

Can you map entity to multiple tables?

Yes, you can map an entity to 2 database tables in 2 simple steps: You need to annotate your entity with JPA's @Table and @SecondaryTable annotations and provide the names of the first and second table as the value of the name parameters.


2 Answers

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

like image 157
Anth12 Avatar answered Oct 26 '22 13:10

Anth12


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

like image 26
Tropin Alexey Avatar answered Oct 26 '22 13:10

Tropin Alexey