Entity Framework 7 中是否有 DbSet<TEntity>.Local 等效项? [英] Is there a DbSet<TEntity>.Local equivalent in Entity Framework 7?

查看:29
本文介绍了Entity Framework 7 中是否有 DbSet<TEntity>.Local 等效项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个

ObservableCollection<TEntity>

在 EF7 中,

DbSet<TEntity>.Local

似乎不存在;

有什么解决办法吗?

推荐答案

当前版本的 EntityFramework (RC1-final) 没有 DbSet.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.

这篇关于Entity Framework 7 中是否有 DbSet&lt;TEntity&gt;.Local 等效项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆