我正在尝试重构一个从DB中提取一些QuerySuggest类型的对象的类。使用Linq对数据库返回的对象进行两次查询。
很明显,这两个查询几乎相同,唯一的区别是前者我有一个附加条件:“&& e.UserId == request.UserId”。
在我看来这是一种代码味道,我想重构它,但我不确定如何继续。
这是我需要重构的代码示例:
IRepository<QuerySuggest> repository = _repositoryManager.GetRepository<QuerySuggest>(_repositoryType);
//entitiesByUser contains all the query suggest by the user
var entitiesByUser = repository.Query(c => c.Where(e => e.IdWebsite == request.WebSiteId &&
e.FulltextFree != null &&
e.DataOra >= (System.DateTime.Today.AddDays(-60).Date) &&
e.UserId == request.UserId)
.GroupBy(g => g.FulltextFree)
.Select(n => new { FulltextFree = n.Key, HowMany = n.Count() })
.Where(w => w.HowMany >= request.HowMany)
.OrderBy(o => o.HowMany))
.ToList();
//entitiesByUser contains all the query suggest not from user
var nonUserEntities = repository.Query(c => c.Where(e => e.IdWebsite == request.WebSiteId &&
e.FulltextFree != null &&
e.DataOra >= (System.DateTime.Today.AddDays(-60).Date))
.GroupBy(g => g.FulltextFree)
.Select(n => new { FulltextFree = n.Key, HowMany = n.Count() })
.Where(w => w.HowMany >= request.HowMany)
.OrderBy(o => o.HowMany))
.ToList();
答案 0 :(得分:1)
我认为这应该是一种方法:
EphemeralKeyRing
答案 1 :(得分:0)
您可以编写一个结合谓词的方法。 @Jon Skeet在这里提供了两种方法:
你应该可以使用这样的东西:
Predicate<YourType> a = e => e.IdWebsite == request.WebSiteId &&
e.FulltextFree != null &&
e.DataOra >= (System.DateTime.Today.AddDays(-60).Date);
Predicate<YourType> b = e => e.UserId == request.UserId;
var entitiesByUser = repository.Query(c => c.Where(Helpers.And(a, b)));