Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a DbSet<TEntity>.Local equivalent in Entity Framework 7?

I need an

ObservableCollection<TEntity>

in EF7,

DbSet<TEntity>.Local

doesn't seem to exist;

Is there any workaround?

like image 543
Yanko Hernández Alvarez Avatar asked Nov 20 '15 04:11

Yanko Hernández Alvarez


People also ask

What does DbSet TEntity class represent in Entity Framework?

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.

What is the difference between DbSet and DbContext?

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.

What is DbSet in Entity Framework Core?

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.

What is local in Entity Framework?

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.


1 Answers

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.

like image 130
Toddams Avatar answered Nov 24 '22 01:11

Toddams