EF Core 10.0 introduces a new approach for mapping complex types in a Entity. Prior to EF Core 10.0, we can manage complex types using Owned Entities.
With EF Core 10.0, we now have a new method ComplexProperty() and in this post let's have a look at the newer approach and possibly do a comparison.
Consider the following.
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public required Address ShippingAddress { get; set; }
public required Address BillingAddress { get; set; }
}
public class Address
{
public required string Street { get; set; }
public required string City { get; set; }
public required string State { get; set; }
public required string PostalCode { get; set; }
}
Now let's see how we can map ShippingAddress and BillingAddress, using Owned Entities vs ComplexProperty.
public class MyDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer("<ConnectionString>");
}
override protected void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Customer>(x =>
{
// Using Owned Entity Types
x.OwnsOne(x => x.ShippingAddress);
// Using Complex Types (new in EF Core 10)
x.ComplexProperty(x => x.BillingAddress);
});
}
}
|
Owned Entity vs ComplexProperty |
For an example, map the properties to different column names, I can do this.
override protected void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Customer>(x =>
{
// Using Owned Entity Types
x.OwnsOne(x => x.ShippingAddress, y =>
{
// Map the properties to different column names
y.Property(p => p.Street).HasColumnName("ShippingStreet");
});
// Using Complex Types(new in EF Core 10)
x.ComplexProperty(x => x.BillingAddress, y =>
{
// Map the properties to different column names
y.Property(p => p.Street).HasColumnName("BillingStreet");
});
});
}
From EF Core 10.0 onwards, ComplexProperty() would be more recommended approach for managing complex types.
Read more:
EF Core 10.0: Complex Types
Hope this helps.
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment