How to update EF Core 2.0 Owned Entities following a DDD aproach?

Viewed 2767

I've a project where I'm using Asp.Net Core 2.0 following a DDD approach. So, I have aggregate roots that owns entities and value objects which are configured as owned types, a new feature in EF Core 2.0. I've added an example of such configuration to better clarify.

Domain:

public class Address : ValueObject 
{
    public Address(string street, int number){
        Street = street;
        Number = number;
    }

    public string Street {get; private set;}
    public int Number {get; private set;}
}  
public class Company : AggregateRoot
{
    public Address Address {get; private set;}
    // Other properties...

    // Value objects are immutables so I'm only able to replace it with a new object.
    public void UpdateAddress(string street, int number){
        Address = new Address(street, number);
    }
    // Other methods...
}

EF Core Entity Configuration:

internal class CompanyEntityTypeConfiguration : IEntityTypeConfiguration<Company>
{
    public void Configure(EntityTypeBuilder<Company> builder)
    {
        builder.HasKey(x => x.Id);
        builder.OwnsOne(x => x.Address);
    }
}

I'm retrieving a tracking entity from the database and when I try to update the AggregateRoot replacing a value object with a new one I get an exception saying that "another entity of the same type is already being tracked". The address is the entity being tracked.

Therefore, the solution was to retrieve an untracked but I don't want to use this approach because it will make a full update in the database. So, how can I update a value object(owned entity) from an entity being tracked by Entity Framework 2.0?

1 Answers
Related