1

我有两种方法,不喜欢重复:

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 子句中)和最后的类似选项时,避免重复的最佳方法是什么?

4

2 回答 2

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<>,但我没有太多经验。

于 2012-08-29T20:53:48.343 回答
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();
}
于 2012-08-29T21:01:46.277 回答