2010-04-19 49 views
0

我得到這個異常 - 「兩個對象之間的關係無法定義,因爲它們連接到不同的ObjectContext對象「。爲什麼是這個異常? - 兩個對象之間的關係無法定義,因爲它們連接到不同的ObjectContext對象

我用戶表和國家表。 countryid在用戶表中被引用。

我正在嘗試在用戶表中添加條目時出現上述異常。

這是我的代碼 -

using (MyContext _db = new MyContext())  
{     
    User user = User .CreateUser(0, Name, address, city, 0, 0, email, zip); 

    Country country = _db.Country.Where("[email protected]", new ObjectParameter("Id",countryId)).First(); 

    user.Country = country; 

    State state = _db.State.Where("[email protected]", new ObjectParameter("Id", stateId)).First(); 

    user.State = state; 

    _db.AddToUser(user);//Here I am getting that Exception 

    _db.SaveChanges();  
} 
+2

順便說一句,你的Where子句可以簡化爲_db.Country.Where(c => c.Id == countryId) – 2010-04-20 05:05:29

回答

1

首先嚐試添加用戶,然後添加關係。

http://www.code-magazine.com/article.aspx?quickid=0907071&page=4

或者不使用User.CreateUser你在哪裏明確設置id = 0的,而使用用戶的用戶=新用戶(){名稱=名稱,地址= ...}

順便說一下,使用Entity Framework 4,您可以直接設置外鍵ID,無需加載相關對象(如果您知道其ID)。

相關問題