2010-09-02 33 views
3

我剛進入實體框架4,最終希望使用POCO將其包裝在存儲庫模式中。我發現了一些我並不期待的事情。看起來,如果你創建一個上下文,向它添加一個對象(不保存上下文)並再次查詢上下文,它不包含結果中的新對象。難道我做錯了什麼?它似乎應該返回我添加的內容,即使我還沒有將結果保存回數據庫。這裏是我的示例代碼:是否可以從未保存的EF4上下文中看到添加的實體?

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 
+0

我遠非一個EF專家。來自NHibernate,我想會有辦法做到這一點。如果沒有,可能會做一個擴展方法或什麼,將執行標準的數據庫查詢和粘性上下文中的項目 - 這似乎很hokey,並希望是不必要的,因爲有一些方法來實現這個在EF開箱即用。 – 2010-09-02 14:11:16

回答

5

的L2E查詢總是從DB返回實體。它將根據查詢的MergeOption將它們與內存中的更改合併。

要看到添加的實體,看看上下文:

var addedCustomers = from se in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added) 
        where se.Entity is Customer 
        select se.Entity; 
+0

所以如果我總是想要什麼在數據庫PLUS什麼被添加到上下文我將不得不做一個工會嗎? – 2010-09-02 14:17:11

+2

你可以,但我通常不會將未保存的實體留在上下文中超過幾微秒。有點取決於你在做什麼。 – 2010-09-02 14:46:39

相關問題