2015-02-10 107 views
4

我有一个包含LINQ查询字符串和我有一个动态的where子句也可以作为包含许多动态条件 这里的字符串是我的where子句创建LINQ查询作为字符串

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

,这里是我的LINQ查询字符串:

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

问题是如何运行此查询并从表中获取结果? 有没有办法做到这一点或Linq不支持这一点?

+0

LINQ查询必须编译时强类型的,像你这样的SQL查询,你不能做到这一点。 – Transcendent 2015-02-10 12:22:31

回答

6

什么你要找的是一样的东西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"); 

这里也是一个很好的起点,它有一个很好的博客文章和一些下载例子。

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

+0

感谢这对我有用 – 2015-02-10 12:50:35

2

也许你会使用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)) 

我不是当然,如果这真的是你想要的,但我认为这是正确的方向。

+0

是否有可能像where字符串那样向where子句添加条件? 我的意思是这样的 context.tblName.Where(“some condtion”) – 2015-02-10 12:32:48

+0

不,它需要强类型。你的用例究竟是什么? – 2015-02-10 12:36:38

+0

我的意思是把这样的条款 context.tblName..Where(“SERIAL_NUMBER == xxx && MAC == xxx”) 我试过但它不接受它 – 2015-02-10 12:40:16

2

我还必须处理动态条件以进行数据库搜索。我想出了这个解决方案,而不是字符串解析或动态LINQ。 errorsOnly,startDateendDate可以(但不一定)在前端设置。可以简单地添加其他条件:

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); 
} 

...等等。这是完全动态的,但同时也是安全的。组装好的SQL查询最终只会被执行一次,当你制作一个列表或类似的IQueryable

0

我想你正在寻找的是动态LINQ。这是由LINQ团队自己提供的图书馆。

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

+0

感谢我现在正在与此图书馆合作,并试图从中找到解决方案。 – 2015-02-10 12:41:47

+0

@Younisbarznji如果这已回答您的问题,请将其标记为答案并关闭此主题。 – JunaidKirkire 2015-02-10 12:42:54