实体框架查询过滤器

发布于 12-02 03:04 字数 85 浏览 2 评论 0原文

是否可以向实体框架对象上下文添加某种全局过滤器?例如,拥有一个 ObjectMaterialized,它可以返回一个指示符,指示是否在结果集中包含给定对象。

Is it possible to add a sort-of a global filter to an Entity Framework object context? Such as having an ObjectMaterialized which can return an indicator of whether or not to include a given object in the result set.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甲如呢乙后呢2024-12-09 03:04:50

不,这是不可能的。实体框架及其内置提供程序不支持全局过滤器。

您可以使用简单的包装器实现一些基本的过滤:

public class MyContext : ObjectContext
{
    private ObjectSet<MyEntity> myEntities;

    public Expression<Func<MyEntity, bool>> GlobalMyEntityFilter { get; set; }

    public IQueryable<MyEntity> MyEntities
    {
        get
        {
            if (GlobalMyEntityFilter != null)
            {
                return myEntities.Where(GlobalMyEntityFilter);
            }

            return myEntities;
        }
    }  
}

No it is not possible. Entity framework and its built in providers don't have any support for global filters.

You can achieve some basic filtering with simple wrapper:

public class MyContext : ObjectContext
{
    private ObjectSet<MyEntity> myEntities;

    public Expression<Func<MyEntity, bool>> GlobalMyEntityFilter { get; set; }

    public IQueryable<MyEntity> MyEntities
    {
        get
        {
            if (GlobalMyEntityFilter != null)
            {
                return myEntities.Where(GlobalMyEntityFilter);
            }

            return myEntities;
        }
    }  
}
怎会甘心2024-12-09 03:04:50

您是否正在尝试做一些类似只显示活跃客户的事情?如果是这样,您可以使用继承并创建一个 ActiveCustomer 类型,并在映射中添加一个条件为 Status == "Active"。 然后将您的 Customer 类型设置为抽象基类以防止直接实例化。然后,您可以在模型中查询 Customers.OfType()。

Are you trying to do something like only show the active Customers? If so, you can use Inheritance and create an ActiveCustomer type and add a condition in your mapping to Status == "Active". Then set your Customer type as an Abstract Base Class to prevent direct instantiation. You can then query your model for Customers.OfType<ActiveCustomer>().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文