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

后端 未结 1 330
梦谈多话
梦谈多话 2020-12-17 18:05

I need an

ObservableCollection

in EF7,

DbSet.Local

doesn\'t seem to exist;

相关标签:
1条回答
  • 2020-12-17 18:46

    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.

    0 讨论(0)
提交回复
热议问题