实体框架 - 更新多对多关系

时间:2012-11-02 21:45:22

标签: sql entity-framework-4

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

这是我的代码:

            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组成的复合主键。

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

谢谢,

0 个答案:

没有答案
相关问题