我有点厌倦了编写这样的服务层代码:
下面的代码只是读者的一个例子.所以他们可能有错误或错别字,抱歉:)
- //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;
- }
我搜索了一些智能设计的代码.我知道Dynamic LINQ库,我也使用它.但我正在寻找强类型过滤.
我不想写魔术字符串或某些字符串.
所以基本上我找到了一些解决方案,但我希望从这个社区中听到一些写得很好的智能代码.当然可能有很多解决方案,但是你又如何编写强类型过滤服务层代码.有任何想法吗…
以下是我的一些解决方案:
解决方案1:
相同的FilterBy方法但参数不同,现在采用表达式列表.所以这意味着我在控制器中创建谓词列表并将其发送到此处.
- 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作为Application Service层(而非域服务)中的参数.我确信这个设计有一些问题,但我想听听你的意见.
- 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,bool>> predicate)
- {
- return filter.Where(predicate);
- }
- }
- public IQueryable<Entity> FilterBy(int? id,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);
- }
我知道这成了一个长长的问题,但我希望我清楚地问我想问什么.
作为一个快速而简单的问题,您是否知道任何设计巧妙的代码,以避免我们编写这些过滤代码的相同行?
顺便说一句,我不是在寻找设计模式解决方案或大答案,你可以给我一些例子或者说如何找到更好的路径就足够了.
当然,如果你写一个完整的解释回复,我会被批评.
谢谢.
解决方法
你试过简单的||条件?
- return _db.Entities
- .Where(x => id == null || x.Id == id.Value)
- .Where(x => startDate == null || x.StartDate >= startDate.Value)
- .Where(x => endDate == null || x.EndDate <= endDate.Value)
- .Where(x => statusId == null || x => x.EntityStatus.StatusID == statusId);