【发布时间】:2013-08-04 06:42:33
【问题描述】:
我有点厌倦了像这样写几行服务层代码:
以下代码仅供读者参考。所以他们可能有错误或拼写错误,对此感到抱歉:)
//ViewModel
public class EntityIndexFilterPartial
{
public int? Id { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public IEnumerable<SelectListItem> StatusList { get; set; }
public int? StatusID { get; set; }
}
//Service Layer method
//Method parameters are reperesents view model properties
public IQueryable<Entity> FilterBy(int? id, DateTime? startDate, DateTime? endDate, int? statusId)
{
var filter = _db.Entities.AsQueryable();
if (id.HasValue)
filter = filter.Where(x => x.Id == id.Value);
if (startDate.HasValue)
filter = filter.Where(x => x.StartDate >= startDate.Value);
if (endDate.HasValue)
filter = filter.Where(x => x.EndDate <= endDate.Value);
if (statusId.HasValue)
filter = filter.Where(x => x.EntityStatus.StatusID == statusId);
return filter;
}
我搜索了一些智能设计的代码。我知道动态 LINQ 库,我也使用它。但我正在寻找强类型过滤。 我不想写魔术字符串或类似的东西。
所以基本上我找到了一些解决方案,但我想从这个社区听到一些写得很好的智能代码。当然可能有几十种解决方案,但你又将如何编写强类型过滤服务层代码。任何想法...
以下是我的一些解决方案:
解决方案 1: 相同的 FilterBy 方法但参数不同,现在采用表达式列表。所以这意味着我正在控制器中创建 predicateList 并将其发送到这里。
public IQueryable<Entity> FilterBy(List<Expression<Func<Entity,bool>>> predicateList)
{
var filter = _db.Entities.AsQueryable();
foreach (var item in predicateList)
{
filter = filter.FilterBy(item);
}
return filter;
}
解决方案 2: FilterBy 方法将 EntityIndexFilterPartial 作为应用程序服务层(不是域服务)中的参数。我确信这个设计有一些问题,但我想听听你的意见。
public IQueryable<Entity> FilterBy(EntityIndexFilterPartial filterPartial)
{
//I'm calling the domain service layer FilterBy method such as like in solution 1.
}
解决方案 3: 我认为这个比其他的要好得多,但我仍在考虑一些更简单和更好的代码。
//helper class
public static class FilterByHelper
{
public static IQueryable<T> If<T>(this IQueryable<T> filter, bool condition, Expression<Func<T, bool>> predicate)
{
if (condition)
return filter.FilterBy(predicate);
return filter;
}
public static IQueryable<T> FilterBy<T>(this IQueryable<T> filter, Expression<Func<T, bool>> predicate)
{
return filter.Where(predicate);
}
}
public IQueryable<Entity> FilterBy(int? id, DateTime? startDate, DateTime? endDate, int? statusId)
{
return _db.Entities
.If(id.HasValue, x => x.Id == id.Value)
.If(startDate.HasValue, x => x.StartDate >= startDate.Value)
.If(endDate.HasValue, x => x.EndDate <= endDate.Value)
.If(statusId.HasValue, x => x.EntityStatus.StatusID == statusId);
}
我知道这个问题有点长,但我希望我清楚地问我想问什么。
作为一个简单而快速的问题,您是否知道任何设计巧妙的代码可以让我们免于编写这些过滤代码的相同行?
顺便说一句,我不是在寻找设计模式解决方案或巨大的答案,你可以给我一些例子或者说如何找到更好的路径就足够了。
当然,如果你写了一个完整的解释性回复,我会很高兴的。
谢谢。
【问题讨论】:
-
这是否与 FindAll(predicate) 方法的工作方式不同?
标签: c# linq strong-typing service-layer