如何在(流畅的)nhibernate中使用QueryOver限制选择?

时间:2011-04-11 09:25:31

标签: nhibernate fluent-nhibernate nhibernate-mapping queryover

我想通过来自另一个对象的属性来过滤数据库中的对象,但我得到一个例外:

  

mscorlib.dll中出现'System.Collections.Generic.KeyNotFoundException'类型的第一次机会异常
  NHibernate.dll中发生了'NHibernate.QueryException'类型的第一次机会异常   NHibernate.dll中发生了'NHibernate.QueryException'类型的第一次机会异常   程序'[5116] Examples.FirstProject.vshost.exe:Managed(v2.0.50727)'已退出,代码为-532459699(0xe0434f4d)。

这有效:

var curves = session.QueryOver<Curve>().WhereRestrictionOn(p => p.Name).IsLike("%CurveName%").List();
foreach (Curve curve in curves)
{
    Console.WriteLine(" ID:\t{0}\n Name:\t{1}\n Group:\t{2}\n", curve.Id, curve.Name, curve.Group.Name);
}

这不是,它输出异常信息:

var curves = session.QueryOver<Curve>().WhereRestrictionOn(p => p.Group.Name).IsLike("%GroupName%").List();
foreach (Curve curve in curves)
{
    Console.WriteLine(" ID:\t{0}\n Name:\t{1}\n Group:\t{2}\n", curve.Id, curve.Name, curve.Group.Name);
}

这些是我的映射:

public class CurveMap : ClassMap<Curve>
{
    public CurveMap()
    {
        Table("CURVES");
        Id(x => x.Id).Column("CURVE_ID");
        Map(x => x.Name).Column("NAME");
        References(x => x.Group).Column("GROUP_ID");
    }
}

public class CurveGroupMap : ClassMap<CurveGroup>
{
    public CurveGroupMap()
    {
        Table("GROUPS");
        Id(x => x.Id).Column("GROUP_ID");
        Map(x => x.Name).Column("NAME");
        HasMany(x => x.Curves).KeyColumn("GROUP_ID").Cascade.All().Inverse();
    }
}

这些是我的对象

public class Curve
{
    public virtual int Id { get; private set; }
    public virtual string Name { get; set; }
    public virtual CurveGroup Group { get; set; }
}

public class CurveGroup
{
    public virtual int Id { get; private set; }
    public virtual string Name { get; set; }
    public virtual IList<Curve> Curves { get; set; }
}

任何想法,如何解决这个问题。我是(流利的)nhibernate的新手。

1 个答案:

答案 0 :(得分:2)

如果您加入CurveGroup并使用别名,它将起作用:

CurveGroup cgAlias = null;
var curves = session.QueryOver<Curve>()
    .JoinAlias(e => e.Group, () => cgAlias)
    .WhereRestrictionOn(() => cgAlias.Name).IsLike("%GroupName%").List();