2011-08-03 212 views
1

我有一個表「Training」,其中有一列「CreatedBy」,它對「用戶」表具有參照完整性。所以「CreatedBy」實際上是一個代表插入訓練記錄的用戶的「用戶」。實體框架添加實體也添加子實體

現在,當我添加一個新的「培訓」實體時,它的「CreatedBy」是一箇舊的「用戶」。所以它不應該嘗試添加用戶。但它確實會失敗,因爲它違反了唯一的關鍵約束。

這是代碼。我哪裏錯了?

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; 
    } 

回答

2

如果您沒有在您身在何處,你添加新的Training必須EF告訴了User已經存在於DB通過將其綁定到上下文你添加新的前相同的上下文加載UserTraining

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; 
}