在使用entity.Children.Clear()
更新实体之前,我已经删除了所有子项:
public static JsonViewData AddOrUpdate(ModelDBContext context, GENCompanyViewModel companyModel, string userName, string userId)
{
try
{
var company = new GENCompany();
if (companyModel.Id > 0) //Update
{
company = context.Companies.Find(companyModel.Id);
context.Entry(company).State = EntityState.Modified;
company.Vehicles.Clear();
company.Phones.Clear();
company.Emails.Clear();
company.InjectFrom(companyModel);
company.DateUpdated = DateTime.Now;
}
else //Add
{
company.InjectFrom(companyModel);
company.CreatedById = new Guid(userId);
context.Companies.Add(company);
context.SaveChanges(userName);
}
if (companyModel.Vehicles.Any())
{
foreach (var vehicleModel in companyModel.Vehicles)
{
var vehicle = context.Vehicles.Find(vehicleModel.Id);
context.Entry(vehicle).State = EntityState.Unchanged;
company.Vehicles.Add(vehicle);
}
}
if (companyModel.Phones.Any())
{
foreach (var phoneModel in companyModel.Phones)
{
var phone = new GENCompanyPhone();
phone.InjectFrom(phoneModel);
company.Phones.Add(phone);
}
}
if (companyModel.Emails.Any())
{
foreach (var emailModel in companyModel.Emails)
{
var email = new GENCompanyEmail();
email.InjectFrom(emailModel);
company.Emails.Add(email);
}
}
context.SaveChanges(userName);
return new JsonViewData { IsSuccess = true, Message = "Added Successfully" };
}
catch (Exception ex)
{
return new JsonViewData { IsSuccess = false, Message = ex.InnerException?.InnerException?.Message ?? ex.InnerException?.Message ?? ex.Message };
}
}
我收到此错误:
操作失败:无法更改关系,因为 一个或多个外键属性是不可为空的。当一个 改变了关系,相关的外键属性是 设置为空值。如果外键不支持空值, 必须定义新的关系,外键属性必须是 分配了另一个非空值,或者不相关的对象必须是 删除。
答案 0 :(得分:0)
问题出现的原因是你试图从一个关系的一端移除某些东西而不是另一端的东西,而另一端的东西是不可为空的。
最简单的解决方案是启用级联删除,然后让EF担心细节,但如果你必须处理这个,那么你需要做的就是删除所有项目,但也在每个项目集上删除相关项目为null,如果不能为null,您也必须删除相关项目。