我有两种方法,不喜欢重复:
public Order LatestOrderOver(decimal amount)
{
return session.QueryOver<Order>()
.Where(o => o.Amount > amount)
.OrderBy(sr => sr.CompleteUtcTime).Desc
.Take(1)
.SingleOrDefault<Order>();
}
public Order LatestAmericanOrderOver(decimal amount)
{
return session.QueryOver<Order>()
.Where(o => o.Amount > amount && o.Country == "USA")
.OrderBy(sr => sr.CompleteUtcTime).Desc
.Take(1)
.SingleOrDefault<Order>();
}
在QueryOver中使用类似标准(在Where子句中)和最后类似选项时,避免重复的最佳方法是什么?
答案 0 :(得分:3)
如果您使用的是Linq To Objects,则可以重构代理:
private Order LatestOrderOver(Func<Order, bool> f) {
return
session.QueryOver<Order>()
.Where(f)
.OrderBy(sr => sr.CompleteUtcTime).Desc
.Take(1)
.SingleOrDefault<Order>();
}
public Order LatestOrderOver(decimal amount) {
return LatestOrderOver(o => o.Amount > amount);
}
public Order LatestAmericanOrderOver(decimal amount) {
return LatestOrderOver(o => o.Amount > amount && o.Country == "USA");
}
否则只需将Func<>
更改为Expression<>
即可,但我对此没有多少经验。
答案 1 :(得分:0)
除了Guffa的建议,您如何看待扩展方法?
public static class QueryOverExtensions
{
public static Order LastOrder(this IQueryOver<Order, Order> query)
{
return query
.Where(o => o.Amount > amount)
.OrderBy(sr => sr.CompleteUtcTime).Desc
.Take(1)
.SingleOrDefault<Order>();
}
// Other query over extension methods
}
然后你可以把你的方法写成:
public Order LatestOrderOver(decimal amount)
{
return session.QueryOver<Order>()
.LastOrder();
}
public Order LatestAmericanOrderOver()
{
return session.QueryOver<Order>()
.Where(o => o.Country == "USA")
.LastOrder();
}