如何通过实体键添加/删除与实体框架的多对多关系? [英] How to add/remove many-to-many relation with entity framework by entity key?

查看:145
本文介绍了如何通过实体键添加/删除与实体框架的多对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过:

  using(Entities e = new Entities())
{
EntityKey key = new EntityKey(Entities.Users,UserId,20);
用户user = new User {EntityKey = key};
角色角色= e.Roles.FirstOrDefault();
//role.Users.Attach(user); // throws(当uncommented ...)InvalidOperationException:
//附加到源对象的对象不会附加到与源对象相同的ObjectContext。
role.Users.Add(user); //抛出InvalidOperationException:
//该对象无法添加到ObjectStateManager,因为它已经有一个EntityKey。使用ObjectContext.Attach附加具有现有密钥的对象。
e.SaveChanges();
}

当尝试使用Remove()而不调用attach时,不会抛出异常

解决方案

尝试这样的一种:

  User user = new User {UserId = 20}; 
e.AttachTo(Users,user);
角色角色= e.Roles.FirstOrDefault();
role.Users.Add(user);
e.SaveChanges();

我发现使用Stub Entities(像上面的用户)而不是EntityKeys更容易使用。 / p>

看到这个博客文章获取关于存根实体技术的更多信息。



希望这有助于



Alex


I tried:

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

When trying to use Remove() without calling attach before no exception is thrown but relation not deleted.

解决方案

Try something like this:

User user = new User {UserId = 20};
e.AttachTo("Users", user);
Role role = e.Roles.FirstOrDefault();
role.Users.Add(user);
e.SaveChanges();

I find it much easier to work with Stub Entities (like the above user) rather than EntityKeys.

See this blog post for more info on Stub Entity techniques.

Hope this helps

Alex

这篇关于如何通过实体键添加/删除与实体框架的多对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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