我正在使用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>
现在我正在尝试创建一个查询,该查询返回与CocktailBar关联的所有Foo对象,其名称为“Nightbar”。如何创建此查询?在NHibernate Reference文档中没有涉及在查询中使用隐式多态(无论是HQL,Criteria还是QueryOver)。
我尝试了以下内容:
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>();
得到异常:“System.InvalidOperationException:NHibernate.Type.AnyType.GetAssociatedEntityName
中的任何类型都没有唯一引用的persister”答案 0 :(得分: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>();