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

时间:2023-01-02 20:17:48

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.

尝试使用Remove()而不调用attach之前没有抛出异常但关系未被删除。

1 个解决方案

#1


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.

我发现使用Stub Entities(比如上面的用户)而不是EntityKeys要容易得多。

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

有关Stub Entity技术的更多信息,请参阅此博客文章。

Hope this helps

希望这可以帮助

Alex

#1


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.

我发现使用Stub Entities(比如上面的用户)而不是EntityKeys要容易得多。

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

有关Stub Entity技术的更多信息,请参阅此博客文章。

Hope this helps

希望这可以帮助

Alex