none
Microsoft.EntityFrameworkCore : Map Entity in two tables RRS feed

  • Question

  • Hello ,

     How I Can map Entity in two tables . in another work I need to split Entity in two tables .

      Thanks,

      Ibrahim


    ASk

    Sunday, January 13, 2019 7:38 AM

All replies

  • You can create entity which is inherited from another entity. First entity has mapped properties to table1 and second entity has properties mapped to table 2. When second entity is inherited from first entity then it has all properties from both tables. First entity can be abstract so you cannot create instance from it. This principle is known as table inheritance.
    Sunday, January 13, 2019 7:59 AM
  • Hello ,

      Thanks fro reply .  How I configure Fluent API to achieve this approach .

      Thanks

         


    ASk

    Sunday, January 13, 2019 8:38 AM
  • Hi himo,

    If you use entity framework 6, you could try the following method.

    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");  
          });  
       }  
    }

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, January 14, 2019 1:30 AM
    Moderator