简体   繁体   中英

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

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

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

you must use Entity splitting

here is an example for it.

I am sharing with you a tutorial link. you can understand the concept of Entity splitting thoroughly. In this tutorial, tutor explains the Entity splitting by a scenario in which he has two tables for user info. in one table he has user name etc and in other table he has user's address. but at application level, there is no separation between user details and user's address. and when user saves data, it goes to two different tables.

here is tutorial link.

you can also download it from torrent for free.

torrent link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM