将 linq 查询创建为字符串

Create linq query as string

我有一个包含 linq 查询的字符串,我有一个动态 where 子句也作为包含许多动态条件的字符串 这是我的 where 子句

string strWhereString = "where a.id==1 && a.name==\"something\"";

这是我的 linq 查询字符串:

var query = "from a in context.tblName "+strWhereString;

问题是如何 运行 这个查询并从 table 中得到结果? 有什么办法可以做到这一点,或者 Linq 不支持这个?

使用 linq 静态方法也许你会更幸运:

context.tblName.Where(a=>a.id==1 && a.name=="something")

这种方式很容易动态添加 where 子句(或其他):

context.tblName..Where(a=>a.id==1 && a.name=="something").Where(a=>otherClause(a))

我不确定这是否真的是您要找的东西,但我认为这是正确的方向。

我还必须处理数据库搜索的动态条件。我想出了这个解决方案,而不是字符串解析或动态 LINQ。 errorsOnlystartDateendDate 可以(但不能)在前端设置。可以简单地相应地添加附加条件:

var query = from x in db.DoubleDataValueArchive select x;
query = query.Where(x => x.DataPointId != null);

// Check if only errors should be shown (that are listed in errorDps)
List<int> errorDps = new List<int>();
if (errorsOnly.HasValue) {
    if (errorsOnly == true)
    {
        errorDps = db.DataPoints.Where(x => x.DataType == 4).Select(x => x.Id).ToList();
        query = query.Where(x => errorDps.Contains((int)x.DataPointId));
    }
}

// Start Date
if (startDate.HasValue) {
    startDate = startDate.Value.ToUniversalTime();
    query = query.Where(x => x.DateValue >= startDate);
}

// End Date
if (endDate.HasValue)
{
    endDate = endDate.Value.ToUniversalTime();
    query = query.Where(x => x.DateValue <= endDate);
}

...等等。这是完全动态的,但同时可以安全使用。当您从 IQueryable.

中创建列表或类似内容时,组装的 SQL 查询只会最终执行一次

我认为您正在寻找的是 Dynamic LINQ。这是LINQ团队自己提供的库

您需要做的是改用字符串表达式,如本博客中所示 - http://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library

您要查找的内容类似于 System.Linq.Dynamic

这将使您能够翻译如下查询:

var query = from p in northwind.Products
                where p.CategoryID == 3 && p.UnitPrice > 3
                orderby p.SupplierID
                select p;

进入:

var query = northwind.Products
                         .Where("CategoryID = 3 AND UnitPrice > 3")
                         .OrderBy("SupplierID");

这也是一个很好的起点,它有一个很好的博客 post 和一些示例可供下载。

Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)