I need an
ObservableCollection<TEntity>
in EF7,
DbSet<TEntity>.Local
doesn't seem to exist;
Is there any workaround?
A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext. Set method.
Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database.
In Entity Framework Core, the DbSet represents the set of entities. In a database, a group of similar entities is called an Entity Set. The DbSet enables the user to perform various operations like add, remove, update, etc. on the entity set.
As you can see in the above output, local keeps track of entities whose state is Added, Modified or Unchanged where as DbSet collection contains all the entities whose state is Deleted, Modified or Unchanged. Visit MSDN for more information on Local.
Current version of EntityFramework (RC1-final) has no DbSet.Local feature. But! You can achieve something similar with current extension method:
public static class Extensions
{
public static ObservableCollection<TEntity> GetLocal<TEntity>(this DbSet<TEntity> set)
where TEntity : class
{
var context = set.GetService<DbContext>();
var data = context.ChangeTracker.Entries<TEntity>().Select(e => e.Entity);
var collection = new ObservableCollection<TEntity>(data);
collection.CollectionChanged += (s, e) =>
{
if (e.NewItems != null)
{
context.AddRange(e.NewItems.Cast<TEntity>());
}
if (e.OldItems != null)
{
context.RemoveRange(e.OldItems.Cast<TEntity>());
}
};
return collection;
}
}
Note: it won't refresh the list if you query for more data. It will sync changes to the list back into the change tracker though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With