自跟踪实体 - 添加到集合时尝试插入未更改的实体
使用 EF4 自我跟踪实体。
我有一个“用户”实体,其中包含用户可以属于的“组”集合。我想向该用户添加/删除一些“组”,仅给出组 ID 列表。
public void UserAddGroups(int userID, List<int> groups)
{
var user = Context.Users.Include("Groups").FirstOrDefault(u => u.ID == userID);
if (user != null)
{
// Iterate through the groups that the user already belongs to.
foreach (var group in user.Groups.ToList())
{
// Remove any groups from the user if the new list does not have it.
if (!groups.Contains(group.ID)) user.Groups.Remove(group);
// Else remove it from the list of new groups to avoid duplication.
else groups.Remove(group.ID);
}
// Iterate through the group list and add it to the user's list
// (only a stubby is created)
foreach (var group in groups) user.Groups.Add(new Group { ID = group }.MarkAsUnchanged());
Context.Users.ApplyChanges(user);
Context.SaveChanges();
}
}
此方法的结果会在 Context.SaveChanges()
处引发错误。该错误报告“Group”实体不允许 Name
属性为 null
。
如果我插入新组,这是预期的,但这显然不是我想要做的。我该如何解决这个问题?
Using EF4 Self-tracking entities.
I have a "User" entity that has a collection of "Groups" the user can belong to. I want to add/remove some "Groups" to this user given just a list of Group IDs.
public void UserAddGroups(int userID, List<int> groups)
{
var user = Context.Users.Include("Groups").FirstOrDefault(u => u.ID == userID);
if (user != null)
{
// Iterate through the groups that the user already belongs to.
foreach (var group in user.Groups.ToList())
{
// Remove any groups from the user if the new list does not have it.
if (!groups.Contains(group.ID)) user.Groups.Remove(group);
// Else remove it from the list of new groups to avoid duplication.
else groups.Remove(group.ID);
}
// Iterate through the group list and add it to the user's list
// (only a stubby is created)
foreach (var group in groups) user.Groups.Add(new Group { ID = group }.MarkAsUnchanged());
Context.Users.ApplyChanges(user);
Context.SaveChanges();
}
}
The result in this method throws an error at Context.SaveChanges()
. The error reports that "Group" entities does not allow null
for Name
property.
This is expected if I were INSERTING new groups, but thats obviously not what I'm trying to do. How can I fix this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你实际上正在插入。通过创建一个新组并将其添加到本质上的集合中,您可以说,这是一个新组,现在添加它。您需要首先从数据库加载该组才能激活对其的跟踪。然后将该组添加到用户组集合中。
amit_g 的解决方案可以工作,但会导致多次数据库调用(每组一个数据库调用)。我会预先加载所有组
You actually ARE inserting. By creating a new group and adding it to the collection in essense you are saying, here is a new group now add it. You need to load the group from the database first to activate tracking on it. then add the group to the users group collection.
amit_g's solution will work but will result in several DB calls ( A DB call per group). I would pre load all the groups up front
尝试一下
Try it with