创建具有实体框架动态查询 [英] Creating dynamic queries with entity framework

查看:142
本文介绍了创建具有实体框架动态查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是创造与实体框架和LINQ动态查询的最佳方式。

I would like to know what is the best way of creating dynamic queries with entity framework and linq.

我要创建一个具有排序和过滤(50)许多参数的服务。我将从GUI而这些将被填掉越来越对象......和查询将从一个单一的服务方法执行。

I want to create a service that has many parameters for sorting and filtering (over 50). I will be getting object from gui where these will be filled out... and query will be executed from a single service method.

我环顾四周,我看到了,我可以动态创建,可在我的方法结束时执行的字符串。我不喜欢这种方式非常多。有没有更好的方式来做到这一点? preferably型与编译检​​查安全吗?

I looked around And I saw that I could dynamically create a string that can be executed at the end of my method. I don't like this way very much. Is there a better way to do this? Preferably type safe with compile check?

推荐答案

您可以撰写的IQueryable< T>一步一步。假设你有一个描述用户希望如何筛选 FilterDefinition 类...

You could compose an IQueryable<T> step by step. Assuming you have a FilterDefinition class which describes how the user wants to filter ...

public class FilterDefinition
{
    public bool FilterByName { get; set; }
    public string NameFrom { get; set; }
    public string NameTo { get; set; }

    public bool FilterByQuantity { get; set; }
    public double QuantityFrom { get; set; }
    public double QuantityTo { get; set; }
}

...那么你可以建立像这样的查询:

... then you could build a query like so:

public IQueryable<SomeEntity> GetQuery(FilterDefinition filter)
{
    IQueryable<SomeEntity> query = context.Set<SomeEntity>();
    // assuming that you return all records when nothing is specified in the filter

    if (filter.FilterByName)
        query = query.Where(t => 
            t.Name >= filter.NameFrom && t.Name <= filter.NameTo);

    if (filter.FilterByQuantity)
        query = query.Where(t => 
            t.Quantity >= filter.QuantityFrom && t.Quantity <= filter.QuantityTo);

    return query;
}

这篇关于创建具有实体框架动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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