【问题标题】:nhibernate queryover join alias with a where-or clausenhibernate queryover join alias with a where-or 子句
【发布时间】:2012-08-19 21:55:02
【问题描述】:

我只是发布代码:

public IList<Dish> GetByNameDishTypes(IEnumerable<string> names,
    IEnumerable<string> dishTypes)
{
    // return dishes (ie food) whose name is in the names enumerable,
    // or whose type is in the dish types enumerables
    // (this would be 'breakfast', 'dinner') ..

    var namesArr = names != null ? names.ToArray() : new string[0];
    var dishTypesArr = dishTypes != null ? dishTypes.ToArray() : new string[0];

    var criteria = this.Session.CreateCriteria<Dish>();
    criteria.CreateAlias("DishType", "dt");
    criteria.Add(
        Restrictions.Or
        (
            Restrictions.In("Name", namesArr),
            Restrictions.In("dt.Name", dishTypesArr)
        ));

    return criteria.List<Dish>();

    /* get this to work?
    Dish d = null;
    DishType dt = null;
    return this.Session.QueryOver<Dish>(() => d)
        .JoinAlias(() => d.DishType, () => dt)
        .Where(
            Restrictions.Or
            (
                Restrictions.In(d.Name, namesArr),
                Restrictions.In(dt.Name, dishTypesArr)
            ))
        .List<Dish>(); */
}

所以,我想知道如何使用 QueryOver 执行此操作。我发布的这个 QueryOver 代码引发了一个空引用异常。标准代码有效。

谢谢你:)

【问题讨论】:

    标签: nhibernate join alias queryover


    【解决方案1】:

    有几种方法可以在 QueryOver 中重写,但最简洁的可能是:

    Dish d = null;
    DishType dt = null;
    return this.Session.QueryOver<Dish>(() => d)
        .JoinAlias(() => d.DishType, () => dt)
        .Where(() => d.Name.IsIn(namesArr) || dt.Name.IsIn(dishTypesArr))
        .List<Dish>();
    

    这将生成如下所示的 SQL:

    SELECT this_.*
    FROM   [Dish] this_
           inner join [DishType] dt1_
             on this_.DishTypeId = dt1_.Id
    WHERE  (this_.Name in (/* Comma separated list of names */)
             or dt1_.Name in (/* Comma separated list of types */))
    

    【讨论】:

    • 尝试做类似的事情。是否有一个特定的using 我必须包含才能使 lambda 正常工作?我收到 () =&gt; d() =&gt; dt 的错误。
    • 无法将 lambda 表达式转换为类型“字符串”,因为它不是 delagate 类型。我在文件顶部包含using System.Linq;using System.Linq.Expressions;。该应用程序的目标是 .Net 4。
    • @Sam:最好打开一个新问题,而不是尝试在此处的 cmets 中解决问题
    • @Andrew,同意了。刚刚在这里发表评论是因为你显然已经让它工作了,所以它可能很简单。
    猜你喜欢
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多