我有一个包含2个子对象的对象: 客户 - 父对象 Customer.Country - 子对象。 关系是:1Country - * Customers,所以我不想创建国家/地区副本。 现在我想使用EF在数据库中创建一个新的Customer对象。
以下是我尝试过的方式:
1:
customer.Country = _context.Countries.Find(p => p.Id ==id);
var obj = _context.Customers.Create(customer);
return _context.SaveChanges() > 0;
2:
Context.Entry(customer.Country).State = EntityState.Unchanged;
Context.Entry(customer).State = EntityState.Added;
return Context.SaveChanges() > 0;
由于一些奇怪的原因,任何一种方式只能工作1次或(最多)2次!然后它弹出错误说我正在尝试插入的子对象已插入... 这很奇怪,所以我检查了状态:子对象的状态是不变的,所以我不明白为什么它说我试图用相同的键插入相同的对象。
操作失败:无法更改关系,因为一个或多个外键属性不可为空。
只有在使用Code First时,我才会遇到此问题。当我使用.edmx时,我没有这个问题。
答案 0 :(得分:1)
创建与现有国家/地区相关的新客户的步骤应为:
如果客户有CountryId道具:
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);