2013-10-26 24 views
0

首先的實體,錯誤是錯誤,同時還與關係

「的實體對象不能被IEntityChangeTracker的多個實例可以參考」我有兩個實體用戶& UsersInHospitals

這是我如何創建一個新的帳戶用戶

var user = new User(); user.UserID = Guid.NewGuid(); user.Address = employmentAddress.Trim(); user.ZipCode = int.Parse(zipcode.Trim()); 

UsersInHospital hospitalAff; 

      hospitalAff = new UsersInHospital() 
      { 
        UserID = user.UserID, 
        HospitalID = Guid.Parse(hospitalAff1), 
        IsEmployed = Boolean.Parse(isEmployed1) 
      }; 
      user.UsersInHospitals.Add(hospitalAff); 

       hospitalAff = new UsersInHospital() 
       { 
        UserID = user.UserID, 
        HospitalID = Guid.Parse(hospitalAff1), 
        IsEmployed = Boolean.Parse(isEmployed2) 
       }; 
       user.UsersInHospitals.Add(hospitalAff); 

,並將其保存

_db.AddToUsers(user); 
return _db.SaveChanges(); //THIS LINE GIVES ME ERROR 

我正在使用實體框架4.我懷疑我將不得不爲每個醫院實體單獨創建變量

回答

0

您必須爲醫院中的用戶創建2個單獨的變量,否則您要添加同一對象的2個引用到您的列表,這就是爲什麼實體框架正在試圖兩次加IEntityChangeTracker相同的對象:

var user = new User 
{ 
    UserID = Guid.NewGuid(), 
    Address = employmentAddress.Trim(), 
    ZipCode = int.Parse(zipcode.Trim()) 
}; 

var hospitalAff1 = new UsersInHospital 
{ 
    UserID = user.UserID, 
    HospitalID = Guid.Parse(hospitalAff1), 
    IsEmployed = Boolean.Parse(isEmployed1) 
}; 

user.UsersInHospitals.Add(hospitalAff1); 

var hospitalAff2 = new UsersInHospital 
{ 
    UserID = user.UserID, 
    HospitalID = Guid.Parse(hospitalAff2), 
    IsEmployed = Boolean.Parse(isEmployed2) 
}; 

user.UsersInHospitals.Add(hospitalAff2); 

也,你不需要在UsersInHospital對象來指定用戶ID。如果您已經正確設置了主鍵和外鍵,實體框架將爲您完成這項工作。然後你的代碼可能看起來像:

var user = new User 
{ 
    UserID = Guid.NewGuid(), 
    Address = employmentAddress.Trim(), 
    ZipCode = int.Parse(zipcode.Trim()), 
    UsersInHospitals = new List<UsersInHospital> //or array or whatever it is 
    { 
     new UsersInHospital 
     { 
      HospitalID = Guid.Parse(hospitalAff1), 
      IsEmployed = Boolean.Parse(isEmployed1) 
     }, 
     new UsersInHospital 
     { 
      HospitalID = Guid.Parse(hospitalAff2), 
      IsEmployed = Boolean.Parse(isEmployed2) 
     } 
    } 
}; 
0

我得到了什麼問題。

其實我用相同HospitalID添加UsersInHospitals,那就是用於校正「用戶ID = user.UserID」爲通過EF自動添加創建重複的實體

由於@Darko的問題。

我已編輯我的問題,以實際顯示問題。對不起,沒有在問題

中顯示此問題