As of EF Core 8, it's now possible to specify a class or a structure as a Complex Type. The following example specifies that the Address
structure should be considered as a complex type:
language-csharp
|
public class Order
{
public int OrderId { get; set; }
public DateTime OrderDate { get; set; }
public Address ShippingAddress { get; set; }
public Address BillingAddress { get; set; }
//... other order-related properties
}
public struct Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string PostalCode { get; set; }
//... other address-related properties
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(x => {
x.ComplexProperty(y => y.ShippingAddress, y => { y.IsRequired(); });
x.ComplexProperty(y => y.BillingAddress, y => { y.IsRequired(); });
});
base.OnModelCreating(modelBuilder);
}
NOTE: When specifying a ComplexProperty
, you must also specify the navigation IsRequired in your fluent mapping.
Data Annotations
The Data Annotations equivalent for the ComplexProperty
method is the ComplexType attribute.