views:

51

answers:

1

I'm just getting into Entity Framework 4, and was eventually hoping to wrap it in a repository pattern using POCOs. I discovered something that I wasn't expecting though. It appears that if you create a context, add an object to it (without saving the context) and query the context again, it doesn't include the new object in the results. Am I doing something wrong? It seems like it should return what I've added, even if I haven't saved the results back to the database yet. Here's 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
+4  A: 

An L2E query always returns entities from the DB. It will merge them with in-memory changes based on the query's MergeOption.

To see added entities, look at the context:

var addedCustomers = from se in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added)
                     where se.Entity is Customer
                     select se.Entity;
Craig Stuntz
so if I always wanted what was in the database PLUS what's been added to the context I would have to do a union right?
Josh Pollard
You could, but I typically don't leave unsaved entities in a context for more than a few microseconds. Kind of depends what you're doing.
Craig Stuntz