Fluent NHibernate Repository with subclasses
Having some difficulty understanding the best way to implement subclasses with a generic repository using Fluent NHibernate.
I have a base class and two subclasses, say:
public abstract class Person
{
public virtual int PersonId { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
}
public class Student : Person
{
public virtual decimal GPA { get; set; }
}
public class Teacher : Person
{
public virtual decimal Salary { get; set; }
}
My Mappings are as follows:
public class PersonMap : ClassMap<Person>
{
public PersonMap()
{
Table("Persons");
Id(x => x.PersonId).GeneratedBy.Identity();
Map(x => x.FirstName);
Map(x => x.LastName);
}
}
public class StudentMap : SubclassMap<Student>
{
public StudentMap()
{
Table("Students");
KeyColumn("PersonId");
Map(x => x.GPA);
}
}
public class TeacherMap : SubclassMap<Teacher>
{
public TeacherMap()
{
Table("Teachers");
KeyColumn("PersonId");
Map(x => x.Salary);
}
}
I use a generic repository to save/retreive/update 开发者_开发技巧the entities, and it works great--provided I'm working with Repository--where I already know that I'm working with students or working with teachers.
The problem I run into is this: What happens when I have an ID, and need to determine the TYPE of person? If a user comes to my site as PersonId = 23, how do I go about figuring out which type of person it is?
NHibernate will manage this for you. The only thing you have to do is query the Person with Id 23. NHibernate will return whatever type this person is casted as its baseclass Person.
Person p = dao.FindById<Person>(23);
if(p is Teacher)
{
Teacher t = (Teacher)p;
}
else if(p is Student)
{
Studet s =(Student)p;
}
This is of course a simple example but i hope it shows the principle of polymorph inheritance. Strategy-pattern and generics are powerfull weapoons against these ugly type checks.
精彩评论