Is it possible to see added objects from an unsaved EF4 context?

I just got into Entity Framework 4 and, in the end, hoped to wrap it in a repository template using POCOs. I discovered something that I did not expect. It seems that if you create a context, add an object to it (without saving the context) and request the context again, it does not include the new object in the results. Am I doing something wrong? It seems that it should return what I added, even if I have not yet saved the results to the database. Here is my sample code:

  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
+3
source share
1 answer

L2E . MergeOption.

, :

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

Source: https://habr.com/ru/post/1762863/


All Articles