EF Core 2.0更新值对象不起作用

时间:2018-03-17 22:49:32

标签: c# entity-framework value-objects

我尝试为EF Core 2.0实现Value Object模式: https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/implement-value-objects

根据Microsoft的示例,我将以下方法添加到Order Aggregate Root:

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

所以我调用此方法并保存更改:

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

但是当我尝试更新它时会抛出以下错误:

  

InvalidOperationException:实体类型的实例...;无法跟踪,因为已经跟踪了具有相同键值的另一个实例。替换所拥有的实体时,修改属性而不更改实例或首先分离先前拥有的实体条目。

价值对象模式从来没有打算更新,或者我做错了什么?

1 个答案:

答案 0 :(得分:0)

此线程对于EF core 2.0 Updating Value Objects非常有用。 总之,请对现有的拥有对象进行突变,而不是设置一个新的对象,例如:

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 
}