6

Consider a Customer entity that has a Resource object representing the logo of the customer:

public class Customer
{
    public Guid Id { get; set; }

    public string CompanyName { get; set; }

    public Resource Logo { get; set; }
}

public class Resource
{
    public string Uri { get; set; }

    public string Name { get; set; }
}

This is what I have tried so far but getting an error because Logo is a complex object:

var customer = modelBuilder.Entity<Customer>().ToTable("Customers");
customer.HasKey(c => c.Id);
customer.Property(c => c.CompanyName).HasColumnName("Company");
customer.Property(c => c.Logo);

How can I store that Resource with EF Core 2.0 as a value object inside the customer table?

2 Answers 2

15

If you want to share the same table you could simply define an Owned Entity:

modelBuilder.Entity<Customer>().OwnsOne(c => c.Logo);

By convention it will use just one table.

Sign up to request clarification or add additional context in comments.

3 Comments

That's what I was looking for! Thank you! (can accept answer in 4 min)
If I need to define the column names of the complex type properties with fluent API, do I do it just as if it was a normal entity? something like modelBuilder.Entity<Resource>().Property(r => r.Name).HasColumnName("ResourceName");
@FercoCQ You need to define those properties inside OwnsOne method: modelBuilder.Entity<Customer>().OwnsOne(c => c.Logo, x => { x.Property(p => p.Logo).HasColumnName("LogoColName"); });
1

Read More About it here there have a exemple
Search with CTRL + F by "Owned entities and Table Splitting"

1 Comment

It is a good starting point, thanks for share, but it doesn't tell so much, for example, how to define the name of the columns in the database, if you don't want the default behavior that you get using only OwnsOne(). Perhaps you could be interested in this documentation: learn.microsoft.com/en-us/ef/core/modeling/owned-entities

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.