1

我在尝试更新表中的多对多类型关系时遇到问题。

这是我的代码:

            foreach (ThingCategory category in this.unit.Context.ThingCategories.Where(c => c.ThingId == thingId))
            {
                if (this.unit.Context.Entry(category).State == EntityState.Detached)
                {
                    this.unit.Context.ThingCategories.Attach(category);
                }

                this.unit.Context.ThingCategories.Remove(category);
            }

            foreach (ThingCategory category in categories)
            {
                if (this.unit.Context.Entry(category).State == EntityState.Detached)
                {
                    this.unit.Context.ThingCategories.Attach(category);
                    this.unit.Context.Entry(category).State = EntityState.Added;
                }
                else
                {
                   this.unit.Context.Entry(category).CurrentValues.SetValues(category);
                   this.unit.Context.Entry(category).State = EntityState.Modified;
                }
            }

            this.unit.Context.SaveChanges();

我越来越:

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

ThingCategory 实体使用由 ThingId 和 CategoryId 组成的复合主键。

有人可以为我指出正确的方向吗?

谢谢,

4

0 回答 0