背景:我正在使用EF6和Database First。爲什麼在調用EF6中的dbContext.Save後重新導航屬性
我遇到了讓我困惑的場景。創建新對象後,使用新對象填充導航屬性並調用SaveChanges,導航屬性將重置。在SaveChanges調用之後引用導航屬性的第一行代碼將最終從數據庫中重新獲取數據。這是預期的行爲,有人可以解釋爲什麼它的行爲如此嗎?這裏是我的場景的示例代碼塊:
using (DbContext context = new DbContext) {
Foo foo = context.Foos.Create();
context.Foos.Add(foo);
...
Bar bar = context.Bars.Create();
context.Bars.Add(bar);
...
FooBar foobar = context.FooBars.Create();
context.FooBars.Add(foobar)
foobar.Foo = foo;
foobar.Bar = bar;
//foo.FooBars is already populated, so 1 is returned and no database query is executed.
int count = foo.FooBars.Count;
context.SaveChanges();
//This causes a new query against the database - Why?
count = foo.FooBars.Count;
}
優秀的解釋,謝謝! – cas4