3

I tried to implement the Value Object pattern for EF Core 2.0: https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/implement-value-objects

According to the example of Microsoft I added following method to the Order Aggregate Root:

public void SetAddress(Address address)
{
    Address = address;
}

So I call this method and save the changes:

orderToUpdate.SetAddress(address);
await _orderRepository.UnitOfWork.SaveEntitiesAsync();

But when I try to update it the following error is thrown:

InvalidOperationException: The instance of entity type ...; cannot be tracked because another instance with the same key value for ... is already being tracked. When replacing owned entities modify the properties without changing the instance or detach the previous owned entity entry first.

Was the Value Object pattern never intended for updating or am I doing something wrong?

Palmi
  • 2,381
  • 5
  • 28
  • 65
  • You should post your code that does the update. – Alaa Masoud Mar 18 '18 at 01:05
  • where is address coming from? To solve the error in your specific case, I think the following passage from your error message is helpful: "When replacing owned entities modify the properties without changing the instance or detach the previous owned entity entry first." – DevilSuichiro Mar 18 '18 at 14:47
  • I have same problem. Can you help anyone please? Value objects are immutable but if I replace them got this error. :( – daremachine Jun 17 '18 at 14:29

1 Answers1

0

This thread was very useful for EF core 2.0 Updating Value Objects. In summary, mutate the existing owned object rather than setting a new one, example:

public void UpdateFrom(string street1, string street2, string city, string state, string zipcode, string country)
{
    StreetAddress1 = street1;
    StreetAddress2 = street2;
    City = city;
    State = state;
    ZipCode = zipcode
}

public void UpdateFrom(Address other)
{
    StreetAddress1 = other.StreetAddress1 ;
    StreetAddress2 = other.StreetAddress2;
    City = other.City ;
    State = other.State;
    ZipCode = other.ZipCode 
}
Denny Puig
  • 632
  • 9
  • 11