Search code examples
nhibernatefluent-nhibernateautomappingone-to-one

fluent nhibernate one-to-one with base class


Suppose I have classes:

class Person
{
 String FirstName;
 String LastName;
 Pet Pet;
}

class Pet
{
 String Name;
 Person Owner;
}

class Cat : Pet
{
 Int32 MousesCaught;
}

class Dog : Pet
{
 Int32 CatsCaught;
}

And a mapping:

public class PetMap : IAutoMappingOverride<Pet>
{
    public void Override(AutoMapping<Pet> mapping)
    {
        mapping.HasOne(x => x.Owner).PropertyRef(x => x.Pet).Constrained().Cascade.All();
        mapping.JoinedSubClass<Cat>("PetId");
        mapping.JoinedSubClass<Dog>("PetId");
    }
}

The problem is: if there is Person with a Cat or a Dog in the DB the type of the Person.Pet is 'Pet{PetBroxyBlaBlaBla}'. So I cannot cast Person.Pet to type Cat (Person.Pet as Cat == null).

    var person = this.Session.Get<Person>(personId);
    // person.Pet as Cat == null

But if I get this pet from DB before getting a Person the type is valid:

    var a = new this.Session.Get<Pet>(petId);
    var person = this.Session.Get<Person>(personId);
    // person.Pet as Cat != null

Is there are a way to tell NHibernate to init this property with a valid type?


Solution

  • Try disabling lazy loading. It can be caused by this