In this post let's see what is Owned Entity Types in Entity Framework Core.
This is a very nice feature when it comes to DDD.
Owned Entities are entities that can be only appeared on navigation properties of other entity types. Basically, they can't exist without the Owner.
Let's go by an example. Consider the following two entities.
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
}
And my DbContext looks like this.
public class MyDbContext : DbContext
{
public DbSet<User> Users { get; set; }
//...
}
So here, we can use OwnsOne to configure the Address
Owned Entity to the Owner User as below (I am using
Fluent API instead of annotations, you can annotations if you prefer, but I
prefer Fluent API all the time).
public class UserEntityConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable($"{nameof(User)}");
builder.OwnsOne(x => x.Address);
}
}
And this will create something like this.
|
dbo.User |
public class UserEntityConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable($"{nameof(User)}");
builder.OwnsOne(x => x.Address, y =>
{
y.Property(y => y.City)
.HasColumnName("City");
y.Property(y => y.Street)
.HasColumnName("Street");
});
}
}
And this would give something like below.
Now let's see consider the following code to insert some data and retrieval.
|
dbo.User |
Now let's see consider the following code to insert some data and retrieval.
using var context = new MyDbContext();
User user = new User
{
Name = "John Doe",
Address = new Address { Street = "Some Street1", City = "Some City1" }
};
await context.Users.AddAsync(user);
await context.SaveChangesAsync();using var anotherContext = new OrderDbContext();
user = await anotherContext.Users.FirstOrDefaultAsync();
Here for selection, EF Core will generate a query as below.
SELECT TOP(1) [u].[Id], [u].[Name], [u].[City], [u].[Street]
FROM [User] AS [u]
So here you should be able to see a very important thing. When we are getting
User, we didn't have to explicitly Include Address to load Address details,
it's loading its Owned Entities by default. This might not be a good example,
since it's in the same table, we will see a clearer example when we are going
through OwnsMany later in this post.
Note: I am using
anotherContext here for retrieval, because EF Core will automatically
fix-up navigation properties to any other entities that were previously loaded
into the context instance. So even if you don't explicitly include the data
for a navigation property, the property may still be populated if some or all
of the related entities were previously loaded.
Above was kind of a one-to-one relationship. Now let's have a look at
one-to-many type of relationship.
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Address> Addresses { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string Type { get; set; }
}
Now I can use OwnsMany as below.
public class UserEntityConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable($"{nameof(User)}");
builder.OwnsMany(x => x.Addresses, y =>
{
y.ToTable("UserAddress");
y.Property(y => y.City)
.HasColumnName("City");
y.Property(y => y.Street)
.HasColumnName("Type");y.Property(y => y.Street)});
.HasColumnName("Type");
}
}
And this would give something like this.
using var context = new MyDbContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();
var user = new User
{
Name = "John Doe",
Addresses = new List<Address>
{
new Address { Street = "Some Street1", City = "Some City1", Type= "Shipping" },
new Address { Street = "Some Street2", City = "Some City2", Type= "Mailing" }
}
};
await context.Users.AddAsync(user);
await context.SaveChangesAsync();
using var anotherContext = new MyDbContext();
user = await anotherContext.Users.FirstOrDefaultAsync();
Here for selection, the generated query would be the following. (you can basically ignore the subquery,
that's because I am getting FirstOrDefault),
SELECT [t].[Id], [t].[Name], [u0].[UserId], [u0].[Id], [u0].[City], [u0].[Street], [u0].[Type]
FROM (
SELECT TOP(1) [u].[Id], [u].[Name]
FROM [User] AS [u]
) AS [t]
LEFT JOIN [UserAddress] AS [u0] ON [t].[Id] = [u0].[UserId]
ORDER BY [t].[Id], [u0].[UserId], [u0].[Id]
And here also, without doing .Include(x => x.Addresses), the addresses are
being returned.
So that's about it. You can read more on Owned Entity Types by going to the below link.
There are some restrictions when it comes to Owned Entities which makes perfect sense.
- You cannot create a DbSet<T> for an owned type.
- You cannot call Entity<T>() with an owned type on ModelBuilder.
- Instances of owned entity types cannot be shared by multiple owners (this is a well-known scenario for value objects that cannot be implemented using owned entity types).
Hope this helps.
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment