Entity Framework Core 2 – Table splitting
Entity Framework Core 2 was released on August 14th. It brought new features.
On this article I will explain one of them : Table splitting
Table carving looks like owned types, but it’s not the same thing.
But an SQL table can be projected in several entities (and not a simple class like the possessed types).
Each entity must have the same primary key, and each entity must be configured and configured separately.
Example:
We will project this table in 2 entities, Product and ProductDetails:
public class Product { public int ProductID { get; set; } public string Name { get; set; } public decimal Cost { get; set; } public ProductDetail Details { get; set; } } public class ProductDetail { public int ProductID { get; set; } public decimal ListPrice { get; set; } public string Size { get; set; } public decimal? Weight { get; set; } public Product Product { get; set; } }
Then let’s configure these 2 entities
- A navigation property from Product to ProductDetails
- A navigation property from ProductDetails to Product
It will we configured as a one to one relationship :
public class ProductConfiguration : IEntityTypeConfiguration<Product> { public void Configure(EntityTypeBuilder<Product> builder) { builder.HasKey(x => x.ProductID); builder.HasOne(e => e.Details).WithOne( o=> o.Product).HasForeignKey<ProductDetail>(e => e.ProductID); builder.ToTable("Product"); } }
public class ProductDetailConfiguration : IEntityTypeConfiguration<ProductDetail> { public void Configure(EntityTypeBuilder<ProductDetail> builder) { builder.HasKey(x=> x.ProductID); builder.HasOne(e => e.Product).WithOne(o => o.Details).HasForeignKey<Product>(e => e.ProductID); builder.ToTable("Product"); } }
It’s identical to two sql tables linked by a one to one relationship.
If you want to get ProductDetails when you quert a Product you must add .Include(“ProductDetails”) extension method to the query, like two sql tables linked by a one to one relationship as well.
Example:
public List<Product> GetProductsWithDetails() { var query = _context.Products.Include(p=> p.Details).ToList(); }
This feature would be commonly used to get from database data you only want to query, it avoids developers to make multiple versions of a same entity, each one used depending the data you want, especially for performance reasons.
So it’s a great feature ?I love it! 🙂