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可能是一篇老文章。。。附加标签