实体框架代码搜索条件 [英] Entity Framework Code First & Search Criteria
问题描述
我正在尝试向我的应用程序添加高级搜索功能。这种高级搜索功能只允许用户输入多个条件进行搜索。例如:
高级产品搜索
- 名称
- 开始日期
- 结束日期
这将允许用户按照产品名称进行搜索,并根据创建日期限制结果。
问题是我不知道有多少这些字段将用于任何单个搜索。那么我的实体框架查询是如何构建的呢?
我有一个例子描述了如何为Entity Framework创建一个动态查询,但是对于我为Code First持久性创建的POCO类似乎不起作用。
当约束数量未知时,构建查询的最佳方法是什么?
所以经过几个小时的这个问题的工作(和我们的朋友谷歌的一些帮助),我找到了一个可行的解决方案,我的问题。我创建了以下Linq表达式扩展:
using System;
使用System.Linq;
使用System.Linq.Expressions;
命名空间MyCompany.MyApplication
{
public static class LinqExtensions
{
public static IQueryable< TSource>其中If< TSource>(这个IQueryable< TSource>源,bool条件,表达式&FunC< TSource,bool>>谓词)
{
if(condition)
return source.Where );
else
返回源;
}
}
}
此扩展程序允许一个Linq查询要这样创建:
var products = context.Products.WhereIf(!String.IsNullOrEmpty(name),p = > p.Name == name)
.WhereIf(startDate!= null,p => p.CreatedDate> = startDate)
.WhereIf(endDate!= null,p => p .CreatedDate< = endDate);
这允许每个WhereIf语句仅在满足提供的条件时才影响结果。解决方案似乎是有效的,但我总是对新的想法和/或建设性的批评开放。
So I have a model created in Entity Framework 4 using the CTP4 code first features. This is all working well together.
I am attempting to add an advanced search feature to my application. This "advanced search" feature simply allows the users to enter multiple criteria to search by. For example:
Advanced Product Search
- Name
- Start Date
- End Date
This would allow the user to search by the product name and also limit the results by the dates that they were created.
The problem is that I do not know how many of these fields will be used in any single search. How then can my Entity Framework query be constructed?
I have an example describing how to create a dynamic query for Entity Framework, however this does not seem to work for the POCO classes I created for Code First persistence.
What is the best way for to construct a query when the number of constraints are unknown?
So after some hours of work on this problem (and some help from our friend Google) I have found a workable solution to my problem. I created the following Linq expression extension:
using System;
using System.Linq;
using System.Linq.Expressions;
namespace MyCompany.MyApplication
{
public static class LinqExtensions
{
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
}
}
This extension allows for a Linq query to be created like this:
var products = context.Products.WhereIf(!String.IsNullOrEmpty(name), p => p.Name == name)
.WhereIf(startDate != null, p => p.CreatedDate >= startDate)
.WhereIf(endDate != null, p => p.CreatedDate <= endDate);
This allows each WhereIf statement to only affect the results if it meets the provided condition. The solution seems to work, but I'm always open to new ideas and/or constructive criticism.
这篇关于实体框架代码搜索条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!