实体框架中必需的AddObject?

时间:2010-05-27 09:21:18

标签: c# sql entity-framework

我在SQL 2005数据库上使用Entity Framework(第一次)进行数据迁移,发现这种奇怪的行为......

到目前为止,我从未调用AddObject方法来保留新记录。 SaveChanges总是这样做,所以我认为实体构造函数总是将新实体挂钩到数据上下文。

现在我添加了另一个实体类型的迁移,突然只有大约20%的记录被保留,所以现在我必须为该实体类型调用AddObject方法。任何人都可以解释这种行为是如何运作的?

1 个答案:

答案 0 :(得分:2)

当您在其某个属性上调用setter并将其设置为已附加(例如,通过相同的上下文加载)实体引用时,Entity Framework看起来会附加一个新实体。

所以:

var myEntity = new MyEntity { Name = "name" }; // will not implicitly add the entity to the context
var myEntity = new MyEntity { OtherEntity = someAttachedEntity }; // will implicitly add the entity to the context