如何从字符串创建LINQ查询? [英] How to create LINQ Query from string?
问题描述
我在LINQ新真的需要一些编码帮助。
I am new at LINQ and really need a help with some coding.
目前,我有一个字符串和一个变种变量。
At the moment, I have a string and a var variables.
string temp = "from product in myEntities.Products where product.Name.Contains(_Name) select product";
var _Products = temp;
LvProducts.DataSource = _Products;
LvProducts.DataBind();
基本上,我想要做的是能够通过分配给它转换成字符串事先创建一个自定义/复杂的LINQ查询。与构成完成后,我分配串入var变量。然而,这显然是行不通的。因此,任何人都可以帮助我在这?
Basically, what I want to do is to be able to create a custom/complicated LINQ query by assigning it into a string beforehand. After done with composing, I assign the string into the var variable. However, this is obviously will not work. Therefore, can anyone assist me on this?
推荐答案
您有几种选择:
-
使用的的动态的LINQ
库来构建你的查询
飞。最好的地方获得
通过阅读<一开始是href=\"http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx\">ScottGu's博客
进入。不过,我不认为
这些库支持包含
方法在你的榜样。 <一href=\"http://blog.walteralmeida.com/2010/05/advanced-linq-dynamic-linq-library-add-support-for-contains-extension-.html\">Here是
一篇博客文章中解释如何添加
这种支持。
Use the the Dynamic Linq libraries to construct you queries on the fly. The best place to get started is by reading ScottGu's blog entry. However, I don't think these libraries support the contains method in your example. Here is a blog post explaining how to add this support.
直接执行SQL 语句。查看MSDN文档为 LINQ to SQL的或的 LINQ到实体。
Directly execute SQL statements. Check out the MSDN docs for Linq to Sql or Linq to Entities.
var _Products = myEntities.ExecuteStoreQuery<Product>
(@"SELECT * FROM Products WHERE [Name] In ('Item1', 'Item2')");
使用的LINQ的组合的行为即可。这可能不是最完美的解决方案,但它的作品真的很好,如果你没有太多的选择。你可以只构造查询多个部分。
Use Linq's composable behaviour. This might not be the most elegant solution but it works really well if you do not have too many options. You can just construct your query in multiple parts.
var _Products = from product in myEntities.Products
select product
_Products = from product in _Products
where product.Name.Contains(_Name)
select product
if FilterByPrice {
_Products = from product in _Products
where product.Price > 100
select product
}
这篇关于如何从字符串创建LINQ查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!