gpt4 book ai didi

c# - 如何通过实体键添加/删除与 Entity Framework 的多对多关系?

转载 作者:行者123 更新时间:2023-11-30 22:49:36 24 4
gpt4 key购买 nike

我试过:

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

我发现使用 Stub Entities(如上述用户)比使用 EntityKeys 更容易。

查看此 blog post有关 stub 实体技术的更多信息。

希望对你有帮助

亚历克斯

关于c# - 如何通过实体键添加/删除与 Entity Framework 的多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1077554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com