gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:14:58 25 4
gpt4 key购买 nike

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

根据微软的例子,我在Order Aggregate Root中添加了如下方法:

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

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

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

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

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.

Value Object 模式从来没有打算用于更新还是我做错了什么?

最佳答案

此线程对 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
}

关于c# - EF Core 2.0 更新值对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49342690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com