我有一个表“Training”,它有一个“CreatedBy”列,它对“User”表有一个参照完整性。所以“CreatedBy”实际上是一个“用户”,代表插入培训记录的用户。
现在当我添加一个新的“Training”实体时,它的“CreatedBy”是一个旧的“User”。所以它也不应该尝试添加用户。但它确实失败了,因为它违反了唯一的键约束。
这是代码。我哪里错了?
public int AddEntity(Training entity, bool isSaveInstantly)
{
this.trainersDeskDBModel.Trainings.AddObject(entity);
if (isSaveInstantly)
{
this.trainersDeskDBModel.SaveChanges();
}
return entity.Id;
}
public int UpdateEntity(Training entity, bool isSaveInstantly)
{
this.trainersDeskDBModel.Trainings.ApplyCurrentValues(entity);
if (isSaveInstantly)
{
this.trainersDeskDBModel.SaveChanges();
}
return entity.Id;
}
public int Save(Training entity, bool isSavedInstantly)
{
IEnumerable<Training> training = this.trainersDeskDBModel.Trainings.Where(x => x.Id == entity.Id);
if (training != null && training.Count() > 0)
{
this.UpdateEntity(entity, isSavedInstantly);
}
else
{
this.AddEntity(entity, isSavedInstantly);
}
return entity.Id;
}
答案 0 :(得分:2)
如果你没有在添加新User
的相同上下文中加载Training
,那么EF必须通过附加它来告诉数据库中已存在User
添加新Training
之前的上下文:
public int AddEntity(Training entity, bool isSaveInstantly)
{
this.trainersDeskDBModel.Users.Attach(entity.CreatedBy);
this.trainersDeskDBModel.Trainings.AddObject(entity);
if (isSaveInstantly)
{
this.trainersDeskDBModel.SaveChanges();
}
return entity.Id;
}