调用的EntityFramework的SaveChanges时重复进行 [英] Entityframework duplicating when calling savechanges
问题描述
我使用的EntityFramework 5代码首先,我有一个这样的模式。
I am using entityframework 5 code first, I have a model like this.
class Product {
public Product() {
Fabrics = new BindingList<FabricLineItem>();
}
...
public virtual ICollection<FabricLineItem> Fabrics { get;set; }
}
class FabricLineItem {
[ForeignKey("Fabric")]
public int FabricId { get; set; }
public virtual Product Product { get;set; }
public virtual Fabric Fabric { get;set; }
}
class Fabric {
...
}
我已经在我的数据库面料。我创建了一个新的产品对象和一些fabriclineitems添加到集合。当我尝试保存产品发生的事情是它复制了织物在数据库中并调用后
I already have fabrics in my database. I create a new product object and add some fabriclineitems to the collection. When I try to save product what happens is it duplicates the fabric in the database and reference it to the new one after calling
DataContext.SaveChanges();
调用的SaveChanges在调试器的值是否正确调用在更改以后过吗?任何想法,为什么我收到这种奇怪的行为?
Before the call to savechanges the values in the debugger are correct by after calling they are changed ? Any idea why I am getting this strange behavior ?
推荐答案
我怀疑是上下文不知道该面料是不是新项目 - 所以它增加了/将它们插入
I suspect that the context does not know that the Fabrics are not new items - so it adds/inserts them.
如果您将面料到DataContext(以不变/ NotModified) - 或从数据库中选择它们,然后当调用SaveChanges()被称为上下文知道现有架构对象,然后可以只为新FabricLineItem导航关系,而无需创建一个新的Fabric
If you attach the fabrics to the DataContext (as Unchanged/NotModified) - or select them from the database, then when SaveChanges() is called the context knows about existing Fabric objects and can then just create a navigation relationship for the new FabricLineItem without creating a new Fabric
EF是很多笨比看起来 - 你真的需要告诉它几乎一切
EF is a lot 'dumber' than it looks - you really need to tell it almost everything.
这篇关于调用的EntityFramework的SaveChanges时重复进行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!