Why is this Exception?- The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

冷暖自知 提交于 2020-01-07 05:23:07

问题


I m getting this Exception-"The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."

I ve user table and country table. The countryid is referred in user table.

I am getting the above Exception when I am trying to add entry in user table.

This is my code-

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

    Country country = _db.Country.Where("it.Id=@Id", new ObjectParameter("Id",countryId)).First(); 

    user.Country = country;

    State state = _db.State.Where("it.Id=@Id", new ObjectParameter("Id", stateId)).First(); 

    user.State = state;

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

    _db.SaveChanges();    
}

回答1:


Try adding the user first, then adding the relationships.

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

Or, don't use User.CreateUser where you are explicitly setting an Id = 0, instead use User user = new User() {Name = Name, Address = ...}

BTW, with Entity Framework 4 you can set the foreign key IDs directly removing the need to load the related object if you know its ID.



来源:https://stackoverflow.com/questions/2666601/why-is-this-exception-the-relationship-between-the-two-objects-cannot-be-defin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!