为什么发生此异常?-无法定义两个对象之间的关系,因为它们被附加到不同的ObjectContext对象 [英] Why is this Exception?- The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

查看:172
本文介绍了为什么发生此异常?-无法定义两个对象之间的关系,因为它们被附加到不同的ObjectContext对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此异常-无法定义两个对象之间的关系,因为它们被附加到不同的ObjectContext对象。

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

用户表和国家/地区表。在用户表中引用了countryid。

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.

这是我的代码-

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


推荐答案

尝试先添加用户,然后添加关系。

Try adding the user first, then adding the relationships.

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

,请勿在要显式设置Id = 0的地方使用User.CreateUser,而应使用User user = new User(){Name = Name,Address = ...}

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

顺便说一句,使用Entity Framework 4,您可以设置外键ID,如果知道它的ID,则直接设置它就无需加载相关对象。

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.

这篇关于为什么发生此异常?-无法定义两个对象之间的关系,因为它们被附加到不同的ObjectContext对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆