I came across a very nice feature of Entity Framework Core that I would like to share with you. It is the owned type.
EF Core’s owned types allow you to group fields that you do not want to appear as a reference, in a separate type.
Let us start with an example. Suppose you have this model. You have Customer and Order and both have fields for an address.
class Customer
{
[Key]
public long CustomerID { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
class Order
{
[Key]
public long OrderID { get; set; }
public bool IsShipped { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
You can easily refactor the previous model by extracting the address fields to a new table and referencing that table in your Customer and Order tables.
class Address
{
[Key]
public long AddressID { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
But what if you want to keep the three address fields inside Customer and Order, and you do want to refactor the code and reduce complexity and duplication, what you are going to do? The answer is in owned entities.
You can update your Address class remove its key field and include a reference in Customer and Order as follows.
class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
class Customer
{
[Key]
public long CustomerID { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
class Order
{
[Key]
public long OrderID { get; set; }
public bool IsShipped { get; set; }
public Address Address { get; set; }
}
Finished? Not yet. You cannot leave your code like this as no entity can be defined without a primary key. Actually, you will get this error if you try to apply your changes to the database.

The next update that we need to do is in the data context itself. We can use the Fluent API to give a hint of how our model will work.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Customer>().OwnsOne(a => a.Address);
modelBuilder.Entity<Order>().OwnsOne(a => a.Address);
}
Now we can apply our model to the database and watch the magic happen.





Jahan AlemPosted Aug 29, 2022, 8:46 PM
Hi Mohammad, Thank you. It was useful. Could you please explain to me about this code? I'd like to know about WithOwner() and HasConversion(): public void Configure(EntityTypeBuilder<Order> builder) { builder.OwnsOne(o => o.ShipToAddress, a => { a.WithOwner(); }); builder.Property(s => s.Status) .HasConversion( o => o.ToString(), o => (OrderStatus) Enum.Parse(typeof(OrderStatus), o) ); builder.HasMany(o => o.OrderItems).WithOne().OnDelete(DeleteBehavior.Cascade); }
Jahan AlemPosted Aug 29, 2022, 8:43 PM
Very nice!