Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 为什么会出现此异常?-无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象_Entity Framework_Entity_Ado - Fatal编程技术网

Entity framework 为什么会出现此异常?-无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象

Entity framework 为什么会出现此异常?-无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象,entity-framework,entity,ado,Entity Framework,Entity,Ado,我得到了一个例外——“无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象。” 我有用户表和国家表。用户表中引用了countryid 当我试图在用户表中添加条目时,出现上述异常 这是我的密码- using (MyContext _db = new MyContext ()) { User user = User .CreateUser(0, Name, address, city, 0, 0, email, zip);

我得到了一个例外——“无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象。”

我有用户表和国家表。用户表中引用了countryid

当我试图在用户表中添加条目时,出现上述异常

这是我的密码-

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

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

或者,不要在显式设置Id=0的位置使用User.CreateUser,而是使用User User=new User(){Name=Name,Address=…}


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

BTW,您的Where子句可以简化为_db.Country.Where(c=>c.ID==countryId)