0

我在 sql server 2008 中创建关系为 1 - * 的拖车表。

table 1: Tour (ID, date, ..) : ID : PK
table 2 : Position (ID,..) : ID : PK, and TourID : FK

Tour tour = new Tour() { ID = 17 /* this ID exist in table tou*/};
Position position = new Position();
position.Tour = tour;
position.Longitude = Longitude;
position.DateHeurePosition = DateH;
db.AttachTo("Tour", tour);
db.AddToPosition(position);
db.SaveChanges();

显示此错误:

ObjectStateManager 中已存在具有相同键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象

如何解决此错误?

4

3 回答 3

0

您可以通过首先分离它来解决这个问题,您可以通过设置新值来更新对象。像这样:

ObjectContext API: context.YourEntitySet.ApplyCurrentValues(newEntity);
DbContext API: context.Entry(oldEntity).CurrentValues.SetValues(newEntity);

我认为您在这里唯一需要的就是找到如下所示的附件

Tour t = Tours.Find(Id);//e.g. Id = 17 where Tours is the DbContext.Set<Tour>
position.Tour = t;

如果您有其他旅行列表:

Tour t = Tours.First(i=> i.Id == Id);//e.g. Id = 17 where Tours is something with interface IEnumarable<Tour>
position.Tour = t;

然后将值设置为该项目的其余部分。

但是如果你想看更复杂的 update 实现,这里是我对 update 方法的实现:

public virtual void Update(T entity)
{
    DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
    var attachedEntity = DbSet.Find(entity.Id);

    if (attachedEntity != null)
    {
        var attachedEntry = DbContext.Entry(attachedEntity);

        entity.Created = attachedEntity.Created;
        entity.LastModified = DateTime.Now;

        attachedEntry.CurrentValues.SetValues(entity);
    }
    else
    {
        dbEntityEntry.State = EntityState.Modified;
        entity.LastModified = DateTime.Now;
    }
}

当您根据需要调整它时,您可以将对象传递给方法,然后保存更改。

于 2013-05-03T11:39:01.120 回答
0

为了解决这个错误,您需要确保您添加的 id 是唯一的。

于 2013-05-03T11:27:18.290 回答
0

您所做的是Tour使用已经存在的 ID 创建了一个新的。

如果要将位置附加到 ID=17 的游览,则必须从数据库中获取所需的记录:

替换position.Tour = tour;
position.Tour = db.Tour.FirstOrDefault(p=>p.ID==17);

于 2013-05-03T11:32:58.277 回答