1

I am using NHibernate 3.2.0 with an Microsoft SQL Server 2005 database, C# 4.0 and the following domain:

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; }
}

and the mapping

<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>

Now I'm trying to create a query that returns all Foo objects that are associated with a CocktailBar that has the name "Nightbar". How do I create this query? Using implicit polymorphism in queries (be it HQL, Criteria or QueryOver) is not covered in the NHibernate Reference documentation.

I tried the following:

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>();

And got the exception: "System.InvalidOperationException : any types do not have a unique referenced persister" in NHibernate.Type.AnyType.GetAssociatedEntityName

MartinB
  • 21
  • 1
  • 6

1 Answers1

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>();
Firo
  • 30,626
  • 4
  • 55
  • 94
  • This gives me an InvalidCastException: Cannot cast from System.RuntimeType to System.String. Even when leaving out lines 3 and 4 the error persists. – MartinB Apr 10 '12 at 09:17
  • typeOf(CocktailBar).Name maybe. I haven't used this a lot – Firo Apr 10 '12 at 09:22
  • Now I get a KeyNotFoudnException. I don't like the SQL generated by NHibernate that causes this error: [ SELECT this_.Id as Id0_0_, this_.TypeOfBarId as TypeOfBa2_0_0_, this_.BarObjectId as BarObjec3_0_0_ FROM NHibernateTest.dbo.POLYTEST_FOO this_ WHERE this_.TypeOfBarId = ? ] Name:cp0 - Value:CocktailBar It tries to compare a string and the Guid in the database, not using the meta-value translation dictionary. – MartinB Apr 10 '12 at 09:37