使用EF保存数据时出现问题 [英] Problem with Saving data using EF
问题描述
我正在尝试使用以下代码保存多对多的关系。当我需要删除关系时,它完美无缺。但是当我需要在表之间添加关系时,我得到以下错误:
Hi,I'm trying to save many to many relationship using code below. When I need to remove relationship it works perfect. But when I need to add relationship between tables then I get the following error:
ObjectStateManager中已存在具有相同键的对象。 ObjectStateManager无法使用相同的键跟踪多个对象。
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
以下是代码:
public class UserRepository : GenericDataRepository<User>, IUserRepository
{
public void SaveManyToManyRelationship(User items)
{
using (var context = new Entities())
{
var existingUser = context.User.Include("Group")
.Where(s => s.UserId == items.UserId).FirstOrDefault<User>();
if (items.ModelEntityState == ModelEntityState.Deleted)
{
foreach (var item in items.Group.Where(i => i.ModelEntityState == ModelEntityState.Deleted))
{
var deletedGroups = existingUser.Group.Where(i => i.GroupId == item.GroupId).ToList<Group>();
deletedGroups.ForEach(c => existingUser.Group.Remove(c));
}
}
else
{
var addedGroups = items.Group.Where(i => i.ModelEntityState == ModelEntityState.Added).ToList<Group>();
//5- Add new groups
foreach (Group c in addedGroups)
{
if (context.Entry(c).State == System.Data.EntityState.Detached)
{
context.Group.Attach(c);
}
existingUser.Group.Add(c);
}
}
context.SaveChanges();
}
}
}
如果有人可以帮助我,请让这最终奏效。我在这做什么提前致谢。
Please if someone can help me in order to make this finally working. What am I doing worng here. Thanks in advance.
Almir
推荐答案
您好Almir,
Hi Almir,
我认为您需要做的就是修改代码以查看实体是否已被跟踪并修改它而不是附加它。 我已经为您的For Each添加了一些代码来说明这一点:
What I believe you need to do to help is to modify your code to see if the entity is already being tracked and modify it rather then attaching it. I've added some code to your For Each to illustrate this:
//5- Add new groups
foreach (Group c in addedGroups)
{
if (context.Entry(c).State == System.Data.EntityState.Detached)
{
var group = context.Group<T>(c);
T attachedEntity = group.Local.SingleOrDefault(e => e.Id == c.Id); // You need to have access to key
if (attachedEntity != null) {
var attachedEntry = context.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(c);
} else {
c.State = EntityState.Modified; // This should attach entity
}
}
existingUser.Group.Add(c);
}
context.SaveChanges();
这篇关于使用EF保存数据时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!