【问题标题】:How to add/remove many-to-many relation with entity framework by entity key?如何通过实体键添加/删除与实体框架的多对多关系?
【发布时间】:2009-07-03 02:28:46
【问题描述】:

我试过了:

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 在没有抛出异常但没有删除关系之前。

【问题讨论】:

  • 在您的 System.Data.Entity.DbContext 类型示例中是“实体”吗?
  • 后研究:如果使用“AttachTo”,那么“Entities”必须是 ObjectContext。
  • LOL 可能,这是一个旧帖子...添加标签

标签: c# entity-framework many-to-many entity-relationship objectcontext


【解决方案1】:

试试这样的:

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

我发现使用存根实体(如上述用户)比使用 EntityKeys 更容易。

有关 Stub Entity 技术的更多信息,请参阅此blog post

希望对你有帮助

亚历克斯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2017-02-14
    • 2017-06-27
    相关资源
    最近更新 更多