[英]Entity Framework - dynamic sql
I'm implementing a search feature for an app that uses entity framework. 我正在为使用实体框架的应用程序实现搜索功能。 There are several optional fields for searching a particular database table/view.
有几个可选字段可用于搜索特定的数据库表/视图。 What is the best way to implement such a search with EF?
用EF实现这种搜索的最佳方法是什么? Stored procedure?
存储过程? Or can it be done (realistically) using Linq only?
还是可以仅使用Linq来(实际上)完成?
A common pattern for handling optional search parameters is to do something like this: 处理可选搜索参数的常见模式是执行以下操作:
string p = null;
var q = from o in dataContext.Products
where ((o.Name == p) || (p == null))
select o;
You should be able to do this in LINQ easily enough. 您应该能够轻松地在LINQ中执行此操作。 Always remember that LINQ queries are chainable:
永远记住LINQ查询是可链接的:
var query = (from p in products
select p);
if(field1 != null)
{
query = (from p in query
where p.Field1 = field1
select p);
}
if(field2 != null)
{
query = (from p in query
where p.Field2 = field2
select p);
}
foreach(Product p in query)
{
// ...
}
What Loren says will work (+1). 劳恩说的有效(+1)。 Or use Microsoft Dynamic LINQ .
或使用Microsoft Dynamic LINQ 。 It works fine with L2E.
它在L2E上正常工作。
您可能会看一下有关动态生成lambda表达式对象来执行此操作的文章 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.