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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.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 实体框架在更新时在两个现有对象之间插入多对多关系_Entity Framework_Insert_Many To Many - Fatal编程技术网

Entity framework 实体框架在更新时在两个现有对象之间插入多对多关系

Entity framework 实体框架在更新时在两个现有对象之间插入多对多关系,entity-framework,insert,many-to-many,Entity Framework,Insert,Many To Many,我正在尝试这样做: using(var context = new SampleEntities()) { User user = select a user from database; //Update user's properties user.Username = ... user.Website = ... //Add a role Role role = select a role from database

我正在尝试这样做:

using(var context = new SampleEntities())
{
     User user = select a user from database;

     //Update user's properties
     user.Username = ...
     user.Website = ...

     //Add a role
     Role role = select a role from  database  
     //trying to insert into table UserRoles which has columns (UserID, RoleID)  
     user.Roles.Add(role); 

     //Apply property changes
     context.ApplyPropertyChanges("Users", user);
     context.SaveChanges();
}
但是,我得到一个异常,告诉我“ObjectContext中的现有对象处于添加状态”,不能“ApplyPropertyChanges”。 如果删除了“ApplyPropertyChanges()”,则会添加一个用户

这些方法的调用顺序是什么?我不需要分开做,对吗?
谢谢。

在我看来,您的用户对象并不是分离的,所以您不需要调用
ApplyPropertyChanges()

@redbluegreen如果您找到了问题的答案,请发布它,以便其他人可以受益。