1

我将 NHibernate 3.2.0 与 Microsoft SQL Server 2005 数据库、C# 4.0 和以下域一起使用:

public class Foo
{
   public virtual Guid Id { get; set; }
   public virtual IBar MyBar { get; set; }
}
public interface IBar
{
   Guid Id { get; set; }
}
public class CocktailBar : IBar
{
   public virtual Guid Id { get; set; }
   public virtual string Name { get; set; }
}
public class ProgressBar : IBar
{
   public virtual Guid Id { get; set; }
   public virtual int Progress { get; set; }
}

和映射

<hibernate-mapping>
   <class name="Foo" table="FOO">
     <id name="Id">
        <generator class="guid.comb"/>
     </id>
     <any name="MyBar" meta-type="System.Guid" id-type="System.Guid">
        <meta-value class="MyNamespace.CocktailBar" value="716B5C04-4115-47BF-BE8A-A3B34D3607FC"/>
        <meta-value class="MyNamespace.ProgressBar" value="65412938-C2DE-48FF-9E90-009881DBDD4F"/>
        <column name="TypeOfBarId"/>
        <column name="BarObjectId"/>
     </any>
   </class>
</hibernate-mapping>

现在我正在尝试创建一个查询,该查询返回与名为“Nightbar”的 CocktailBar 关联的所有 Foo 对象。如何创建此查询?在查询中使用隐​​式多态性(无论是 HQL、Criteria 还是 QueryOver)并未包含在 NHibernate 参考文档中。

我尝试了以下方法:

Foo theFoo = session.QueryOver<Foo>()
         .Where(c => c.MyBar.GetType().Name == "CocktailBar")
         .JoinQueryOver<IBar>(c => c.MyBar)
         .Where(c => ((CocktailBar)c).Name == "Nightbar")
         .SingleOrDefault<Foo>();

并得到了例外: NHibernate.Type.AnyType.GetAssociatedEntityName 中的“System.InvalidOperationException:任何类型都没有唯一引用的持久性”

4

1 回答 1

0
Foo theFoo = session.QueryOver<Foo>()
     .Where(Restrictions.Eq("MyBar.class", typeOf(CocktailBar))) <-- here
     .JoinQueryOver<IBar>(c => c.MyBar)
     .Where(c => ((CocktailBar)c).Name == "Nightbar")
     .SingleOrDefault<Foo>();
于 2012-04-07T11:45:35.350 回答