10

Entity Framework ObjectSet with its method ToList shows just saved entities. That means, when I call

context.AddToCustomers(myNewCust);

and then (without calling SaveChanges)

myDataGrid.DataContext = context.Customers.ToList();

the DataGrid doesn't show the newly added entity (even context.Customers.Count() doesn't include it).

Is there any way to show these entities (those with EntityState = Added) ?

Thanks in advance.

Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134
Mix Net
  • 103
  • 1
  • 4

2 Answers2

10

I think you can get unsaved added entities by calling something like:

var inserted = context.ObjectStateManager
                      .GetObjectStateEntries(EntityState.Added)
                      .Where(e => !e.IsRelationship)
                      .Select(e => e.Entity)
                      .OfType<Cutomer>();

But just by reading your question, I'm affraid that you are trying to do something wrong. Why do you need to combine unsaved entities with retrieved? If you need to show unsaved content you should simply keep it in your own separate collection.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • "Why do you need to combine unsaved entities with retrieved?" Perhaps you have an Entity in a form with related children entities displayed in a list - you want to add new children to the list but only persist the children when they save the parent entity. – markmnl Nov 09 '12 at 01:50
2

Look at the TryGetObjectStateEntry(EntityKey, ObjectStateEntry) method

http://msdn.microsoft.com/en-us/library/system.data.objects.objectstatemanager.aspx

sajoshi
  • 2,733
  • 1
  • 18
  • 22