Entity Framework allows to divide a single entity to 2 separate physical tables. To do this you need to declare an entity as usual, and add a Fluent API command to map this entity to tables.
Declaration of entity:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[Table("ClientTable", Schema = "dbo")] public class Client { [Key] public int Id { get; set; } [Required] [StringLength(10)] public string Code { get; set; } [StringLength(100)] public string Name { get; set; } public string Comment { get; set; } } |
Table annotation is not necessary here and will be omitted by Visual Studio.
Entity-table mapping:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // splitting entity into 2 tables modelBuilder.Entity<Client>() .Map(m => { m.Properties(p => new { p.Id, p.Code, p.Name }); m.ToTable("Client", "dbo"); } ) .Map(m => { m.Properties(p => new { p.Id, p.Comment }); m.ToTable("ClientData", "dbo"); } ); } |
After migration Entity Framework will create 2 tables with the names defined in OnModelCreating function.
In Entity Framework you work with a single entity, i.e. you can create/update entity as usual, but when you save changes, the database context will generate separate SQL commands to modify the corresponding tables (first, second or both).
Be aware if you skip a property in mapping, Entity Framework will create a 3rd table with key field and a new created one.