Jos*_*ard 3 entity-framework entity-framework-4
我刚刚进入实体框架4,并最终希望使用POCO将其包装在存储库模式中.我发现了一些我没想到的东西.看来,如果您创建上下文,向其添加对象(不保存上下文)并再次查询上下文,则它不会在结果中包含新对象.难道我做错了什么?它似乎应该返回我添加的内容,即使我还没有将结果保存回数据库.这是我的示例代码:
ShopEntities context = new ShopEntities();
// there is only 1 customer so far
var customers = from c in context.Customers
select c;
Console.WriteLine(customers.Count()); // displays 1
Customer newCustomer = context.Customers.CreateObject();
newCustomer.FirstName = "Joe";
newCustomer.LastName = "Smith";
context.Customers.AddObject(newCustomer);
var customers2 = from c in context.Customers
select c;
Console.WriteLine(customers2.Count()); // still only displays 1
context.SaveChanges();
var customers3 = from c in context.Customers
select c;
Console.WriteLine(customers3.Count()); // only after saving does it display 2
Run Code Online (Sandbox Code Playgroud)
L2E查询始终从DB返回实体.它将根据查询将它们与内存中的更改合并MergeOption.
要查看添加的实体,请查看上下文:
var addedCustomers = from se in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added)
where se.Entity is Customer
select se.Entity;
Run Code Online (Sandbox Code Playgroud)