使用 EF CF 将复杂对象插入数据库的奇怪问题



我有一个包含 2 个子对象的对象:客户 - 父对象客户国家/地区 - 子对象。关系是:1国家 - *客户,所以我不想创建国家重复项。现在,我想使用 EF 在数据库中创建一个新的客户对象。

这些是我尝试的方法:

1:

customer.Country = _context.Countries.Find(p => p.Id ==id);
var obj = _context.Customers.Create(customer);
return _context.SaveChanges() > 0;

阿拉伯数字:

Context.Entry(customer.Country).State = EntityState.Unchanged;
Context.Entry(customer).State = EntityState.Added;
return Context.SaveChanges() > 0;

出于某种奇怪的原因,任何一种方式都只能工作 1 次或(最多)2 次!然后它会弹出错误,说我尝试插入的子对象已经插入......这很奇怪,所以我检查了状态:子对象的状态是 Unchanged,所以我不明白为什么它说我试图使用相同的键插入相同的对象。

操作失败:无法更改关系,因为一个或多个外键属性不可为空。

只有当我使用代码优先时,我才会遇到这个问题。当我使用 .edmx 时,我没有这个问题。

创建与现有国家/地区相关的新客户的步骤应为:

如果客户有国家/地区 ID 属性:

var newCust = new Customer
{
    CountryId = existingCountryId,
    ...
};
_context.Customers.Add(newCust);

否则

var existingCountry = _context.Countries.Find(existingCountryId);
// or create an Country object with the corresponding Id and attach to the context
var newCust = new Customer
{
    Country = existingCountry,
    ...
};
_context.Customers.Add(newCust);