关于 Table<TEntity>.Attach(),据说它的作用就是可以在不同的DataContext当中附加数据,让被附加的数据(实体)即使在外部(DataContext上下文之外)修改也可以让别的DataContext中的对应数据得以更新。
假设我已经有一个Category的实体类与对应的数据库表。
相关类代码如下:
1
public class DataAccess
2
}
2
1
static void Main(string[] args)
2
}
2
为什么当我不设断点的时候,会出现Exception:
"An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported."
当我在13行 DataAccess.Attach(category);处设了一个断点,而且用鼠标放在category上查看了一下属性值,继续运行,它就不会出错,一切正常了!!!!
是什么原因啊?????
---------------------------------------------------------------------
经大侠指引,终天知道原来因为Category 表中有一个外键,对于实体类Category, 有一个字段:
private EntityRef<Parent>
必须在调用 Attach()方法之前,先令
_Parent=default(EntityRef<Parent>
综上所述,为了方便使用,我在Category类中加了一个Detach()方法:
必须在调用 Table<TEntity>.Attach()方法之前,先调用category.Detach()方法。