ef核心为多个实体设置了相同的值对象

时间:2020-09-04 11:14:41

标签: c# entity-framework .net-core entity-framework-core ef-core-3.1

我将EF Core 3.1与CosmosDB结合使用,并尝试实现一些DDD方法。 我有客户实体

public class Customer : Entity, IAggregateRoot
{
    // For EF Core
    protected Customer()
    {
    }

    public Customer(Guid id, string name, Address address)
    {
        CustomerId = id;
        Name = name;
        SetAddress(address);
    }

    public Guid CustomerId { get; private set; }
    public string Name { get; private set; }
    public Address Address { get; private set; }

    public void SetAddress(Address address)
    {
        Address = address ?? throw new ValidationException(nameof(Address), "Required");
    }
}

并将地址作为值对象:

public class Address
{
    // For EF Core
    public Address()
    {
    }

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

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

实体配置为:

builder.ToContainer("Customers");
builder.HasNoDiscriminator();
builder.HasKey(x => x.CustomerId);    
builder.OwnsOne(x => x.Address);

我需要从数据库中获取客户列表,然后为其更新地址。

var customers = await _repository.GetAll(x => x.Name == "Joe", cancellationToken);
var address = new Address("St1", "London", "", "UK");
foreach (var customer in customers)
{
   customer.SetAddress(address);
   _repository.Update(customer);
}
await _repository.Save(cancellationToken);

假设我在customers中只有2个项目。在Save之后,我将为第一项得到null,为第二项得到ne地址。不知道为什么。但是,当我为循环中的每个项目创建一个新地址时,一切都很好

foreach (var customer in customers)
{
   customer.SetAddress(new Address("St1", "London", "", "UK"););
   _repository.Update(customer);
}

请问我为什么每次都要创建一个新对象?

1 个答案:

答案 0 :(得分:1)

我相信这是因为EF Core跟踪类实例。

在第一个迭代中,您将地址放入了第一个客户,EF Core开始跟踪它。当您将其发送给第二位客户时,EF Core会将其视为将同一地址从一位客户转移到另一位客户。