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



我尝试实现EF Core 2.0的值对象模式:https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/implement-value-objects

根据Microsoft的示例,我将以下方法添加到订单聚合根中:

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

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

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

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

无效操作异常: 无法跟踪实体类型 ...; 的实例,因为另一个实例具有相同的键值...已被跟踪。替换拥有的实体时,在不更改实例的情况下修改属性,或者先分离以前的拥有实体条目。

值对象模式从未打算更新还是我做错了什么?

此线程对于 EF core 2.0 更新值对象非常有用。总之,改变现有的拥有对象而不是设置一个新对象,例如:

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 
}

相关内容

  • 没有找到相关文章

最新更新