SHARE:

Entity Framework Core 2 – Owned types

 

Entity Framework Core 2 was released on August 14th. It brought new features.

On this article I will explain one of them : Owned types

They existed in previous versions of Entity Framework under the name of “complex types” and then disappeared from Entity Framework Core 1
It is a grouping of fields of the same SQL table in a type belonging to the entity corresponding to the same SQL table.

Example, we want to group in table Person properties : FirstName, MiddleName, LastName under a subtype named Name:

 

 

This table will be mapped like this:

public class Person
{
   public int BusinessEntityID { get; set; }
   public Name Name { get; set; }
}

public class Name
{
   public string FirstName { get; set; }
   public string MiddleName { get; set; }
   public string LastName { get; set; }
}

Configuration required:

You must declared in the primary entity Person a key, then you have to map your properties FirstName, MiddleName, LastName to the subtype Name.

Example:

public class PersonConfiguration : IEntityTypeConfiguration<Person>
{
   public void Configure(EntityTypeBuilder<Person> builder)
   {
      builder.HasKey(x => x.BusinessEntityID);
      builder.OwnsOne(x => x.Name).Property(c=> c.FirstName).HasColumnName("FirstName");
      builder.OwnsOne(x => x.Name).Property(c => c.MiddleName).HasColumnName("MiddleName");
      builder.OwnsOne(x => x.Name).Property(c => c.LastName).HasColumnName("LastName");
      builder.ToTable("Person", "Person");
   }
}

So Person owns Name

Usage:

 

 

Glad to see this feature come back? 🙂

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: