Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.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
C# 如何通过实体键添加/删除与实体框架的多对多关系?_C#_Entity Framework_Many To Many_Entity Relationship_Objectcontext - Fatal编程技术网

C# 如何通过实体键添加/删除与实体框架的多对多关系?

C# 如何通过实体键添加/删除与实体框架的多对多关系?,c#,entity-framework,many-to-many,entity-relationship,objectcontext,C#,Entity Framework,Many To Many,Entity Relationship,Objectcontext,我试过: using (Entities e = new Entities()) { EntityKey key = new EntityKey("Entities.Users", "UserId", 20); User user = new User { EntityKey = key}; Role role = e.Roles.FirstOrDefault(); //role.Users.Attach(user); //throws (when uncomme

我试过:

using (Entities e = new Entities())
{
    EntityKey key = new EntityKey("Entities.Users", "UserId", 20);
    User user = new User { EntityKey = key};
    Role role = e.Roles.FirstOrDefault();
    //role.Users.Attach(user); //throws (when uncommented...) InvalidOperationException:
    //The object being attached to the source object is not attached to the same ObjectContext as the source object.
    role.Users.Add(user); //throws InvalidOperationException too:
    //The object cannot be added to the ObjectStateManager because it already has an EntityKey. Use ObjectContext.Attach to attach an object that has an existing key.
    e.SaveChanges();
}

在未引发异常但未删除关系之前尝试使用Remove()而不调用attach时。

请尝试以下操作:

User user = new User {UserId = 20};
e.AttachTo("Users", user);
Role role = e.Roles.FirstOrDefault();
role.Users.Add(user);
e.SaveChanges();
我发现使用存根实体(如上面的用户)比使用EntityKey容易得多

有关存根实体技术的更多信息,请参见本文

希望这有帮助


Alex

在您的System.Data.Entity.DbContext类型示例中是“Entities”吗?后期研究:如果使用“AttachTo”,那么“Entities”必须是ObjectContext。LOL可能是一篇老文章。。。附加标签