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

后端 未结 1 333
梦谈多话
梦谈多话 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 GetLocal(this DbSet set)
            where TEntity : class
        {
            var context = set.GetService();
            var data = context.ChangeTracker.Entries().Select(e => e.Entity);
            var collection = new ObservableCollection(data);
    
            collection.CollectionChanged += (s, e) =>
            {
                if (e.NewItems != null)
                {
                    context.AddRange(e.NewItems.Cast());
                }
    
                if (e.OldItems != null)
                {
                    context.RemoveRange(e.OldItems.Cast());
                }
            };
    
            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)
提交回复
热议问题