Entity Framework核心:无法使用嵌套值对象更新实体

Entity Framework Core: Fail to update Entity with nested value objects

我有一个实体,它有一个值对象,这个值对象有另一个值对象。我的问题是,当更新实体和值对象时,具有父值对象的实体得到更新但子值对象没有。 注意,我使用了最新版本的 Entity Framework Core 2.1.0-rc1-final.

这是父实体 Employee:

public class Employee : Entity
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }
    public string Email { get; private set; }
    public Address Address { get; private set; }
}

这是父值对象Address:

public class Address : ValueObject<Address>
{
    private Address() { }

    public Address(string street, string city, string state, string country, string zipcode, GeoLocation geoLocation)
    {
        Street = street;
        City = city;
        State = state;
        Country = country;
        ZipCode = zipcode;
        GeoLocation = geoLocation;
    }

    public string Street { get; private set; }
    public string City { get; private set; }
    public string State { get; private set; }
    public string Country { get; private set; }
    public string ZipCode { get; private set; }
    public GeoLocation GeoLocation { get; private set; }
}

这是子值对象GeoLocation:

public class GeoLocation
{
    private GeoLocation()
    {

    }

    public GeoLocation(decimal longitude, decimal latitude)
    {
        Latitude = latitude;
        Longitude = longitude;
    }
    public Decimal Longitude { get; private set; }
    public Decimal Latitude { get; private set; }
}

并且在更新员工时,我首先从数据库中获取它,然后使用从用户界面获取的新值更改 Address 属性。

var employee = _repository.GetEmployee(empId);
employee.SetAddress(newAddress);

SetAddress方法:

public void SetAddress(Address address)
{
    Guard.AssertArgumentNotNull(address, nameof(address));
    Address = address;
}

根据 this EF Core GitHub ticket,您必须直接更新 child/nested/owned 类型属性才能正确跟踪。这本应在 EF 2.1 中修复(目前仅作为候选发布版提供),但可能尚未完成。在 2.0.3 中,他们将异常的措辞更新为:

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

如果您正在使用 DDD,此消息的第二部分会让您有点吐。它告诉您必须直接更新 child/nested 属性的属性,以便 EF 正确跟踪更改(这打破了 DDD 值对象的不可变性)。根据 comment on the GitHub thread,这里有一个建议的、有点 DDD 友好的解决方法,适合您的代码:

public void SetAddress(Address address)
{
    Guard.AssertArgumentNotNull(address, nameof(address));    
    Address.UpdateFrom(address);
}
// And on Address:
internal void UpdateFrom(Address other)
{
    Street = other.Street;
    // ...
}

-或-

第二种建议的解决方法是分离实体,更新 Address 的实例,然后重新附加它。在我的实现中,我对这个变通办法运气不佳,但 post 为了 post 诚实。也许你的运气会比我好。

context.Entry(employee.Address).State = EntityState.Detached;
employee.SetAddress(newAddress);
context.Entry(employee.Address).State = EntityState.Modified;

更新

我终于找到了可以跟踪此问题的 EF Core 团队的公开票证。 Ticket #10551 明确说明了手头的问题,并且仍未解决。它肯定没有出现在 EF Core 2.1 中,并且似乎已被放置在 Backlog Milestone 3.0 中。请注意,您可以对该问题进行投票,以此作为让 EF Core 团队更加关注它的一种方式。

更新 2 EF Core 2.2 引入了一个 Tracked Graph 组件,使这更加流畅。但是,这确实需要您的所有 EF 实体都使用数据库生成的 ID。此方法检查是否设置了实体键,然后将实体标记为已修改或已添加。这可以扩展为包括删除,但出于我的目的,我不希望出现这种行为。

internal void Upsert(object entity)
{
    ChangeTracker.TrackGraph(entity, e =>
    {
        if (e.Entry.IsKeySet)
        {
            e.Entry.State = EntityState.Modified;
        }
        else
        {
            e.Entry.State = EntityState.Added;
        }
    });

    #if DEBUG
    foreach (var entry in ChangeTracker.Entries())
    {
        Debug.WriteLine($"Entity: {entry.Entity.GetType().Name} State: {entry.State.ToString()}");
    }
    #endif
}

然后,在context.SaveChanges();之前使用context.Upsert(<YOUR ENTITY OBJECT>);

可以在

找到更简单的替代方法

简而言之,而不是

_context.Entry(contactModelFromRequestBody).State = EntityState.Modified;

你应该使用

_context.Update(contactModelFromRequestBody);