Fluent NHibernate inheritance mapping problem

2019-05-24 03:26发布

问题:

I am using Fluent NHibernate with table per subclass inheritance mapping. I want to reference to a list of specific objects, but i can't figure out, how to restict the result to objects of one specific class.

class PetMap : ClassMap<Pet>
{
    public PetMap()
    {
        Id(c => c.ID).GeneratedBy.Identity();            
    }
}

class DogMap : ClassMap<Dog>
{
    public DogMap()
    {
       Mac(c => c.DogSpecificProperty);                                
    }
}

class CatMap : SubclassMap<Cat>
{
    public CatMap()
    {
       Mac(c => c.CatSpecificProperty);                                    
    }
}

class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {  
        Id(c => c.ID).GeneratedBy.Identity();

        //this works fine
        HasMany(c => c.Pets);

        //this dosen't work, because the result contains dogs and cats
        //how can I tell NHibernate to only fetch dogs or cats?
        HasMany<Pet>(c => c.Cats);
        HasMany<Pet>(c => c.Dogs);
    }
}

class Pet
{ 
   int ID;
}
class Dog : Pet
{
   object DogSpecificProperty;
}
class Cat : Pet
{
   object CatSpecificProperty;
}
class Person
{
   int ID;
   IList<Pet> Pets;
   IList<Dog> Dogs;
   IList<Cat> Cats;
}

Can anyone help me? Please excuse my poor english.

回答1:

I'm not an expert in Fluent NH, but it seems to me that your person map should look like this:

class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {  
        Id(c => c.ID).GeneratedBy.Identity();

        //this works fine
        HasMany(c => c.Pets);

        //this dosen't work, because the result contains dogs and cats
        //how can I tell NHibernate to only fetch dogs or cats?
        HasMany<Cat>(c => c.Cats);
        HasMany<Dog>(c => c.Dogs);
    }
}

Because you're Person has a Dogs property which is an IList not IList, and conversely the same for Cats.