开发者

NHibernate can not retrieve typeof a derived class correctly

Hello

Short and to the point, I have 3-level inheritance :

public class JobBase
{
    virtual public Guid Id { get; set; }
    // Some properties here
}
public class Job:JobBase
{
    // Some properties here
}
public class JobTypeX : Job
{
    // Some properties here
}
public class JobTypeY : Job
{
    // Some properties here
}

Mappings :

public class JobBaseMap : ClassMap<JobBase>
{
    public JobBaseMap()
    {
        Id(p => p.Id);
        //other mappings
    }
}
public class JobMap : SubclassMap<Job>
{
    public JobMap()
    {
        KeyColumn("JobBaseId");
        //other mappings
    }
}
public class JobTypeXMap : SubclassMap<JobTypeX>
{
    public JobTypeXMap()
    {
        KeyColumn("JobBaseId");
        //other mappings

    }
}
public class JobTypeYMap : SubclassMap<JobTypeY>
{
    public JobTypeYMap()
    {
        KeyColumn("JobBaseId");
        //other mappings

    }
}

Another class which uses Job

public class Person
{
  virtual public Guid Id { get; set; }
  virtual public Job MyJob { get; set; }
}

well, when I want to add a new Person I write somthing like :

        Person person = new Person();

        //set other properties
        //jobId can be either JobTypeX's id or JobTypeY's id 

        person.MyJob = Repository<Job>.Get(jobId);

        //surely, one of conditions is true 
        if (person.MyJob is JobTypeX)
        {
            //do something
        }
        else if (person.MyJob is JobTypeY)
        { 
            //do sth else here
    开发者_如何学C    }

        Repository<Person>.Save(person);

So far so good. It loads the same data by the code below :

        Person person = Repository<Person>.Get(personId);

Although all the values of person.MyJob is correct when person is loaded, it cannot recognize the Job type anymore :

        if (person.MyJob is JobTypeX)  // false
        {
            //do something
        }
        else if (person.MyJob is JobTypeY) // false
        {
            //do sth else here
        }

There are a few ways to get rid of this problem. For example, I can check whether JobBaseId is available in table JobTypeX or JobTypeY. but I guess something should be wrong somewhere!

do I miss something? any idea?


This is by design (see http://ayende.com/Blog/archive/2009/09/03/answer-the-lazy-loaded-inheritance-many-to-one-association-orm.aspx)

For a workaround, see http://sessionfactory.blogspot.com/2010/08/hacking-lazy-loaded-inheritance.html

I also suggest you read about http://en.wikipedia.org/wiki/Liskov_substitution_principle

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜