I'm new to Fluent NHibernate, thus far I managed to get my mapping working except for the inheritance part. Is there anybody who could help me finish the mapping? I have simplified the code as much as possible.
Thank you!
My database:
CREATE TABLE [User] (
UserID INT NOT NULL IDENTITY(1,1),
Type CHAR(1) NOT NULL,
Email VARCHAR(255) NOT NULL,
PRIMARY KEY(UserID)
);
CREATE TABLE [Student] (
UserID INT NOT NULL,
Firstname VARCHAR(255) NOT NULL,
PRIMARY KEY(UserID),
FOREIGN KEY(UserID) REFERENCES [User](UserID)
);
CREATE TABLE [Company] (
UserID INT NOT NULL,
Name VARCHAR(255) NOT NULL,
PRIMARY KEY(UserID),
FOREIGN KEY(UserID) REFERENCES [User](UserID),
);
My classes:
public class User
{
public virtual int UserID { get; set; }
public virtual UserType Type { get; set; }
public virtual string Email { get; set; }
public User()
{
}
}
public class Student : User
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public Student()
: base()
{
}
}
public class Company : User
{
public virtual string Name { get; set; }
public Company()
: base()
{
}
}
public enum UserType
{
STUDENT = 0,
COMPANY = 1
}
Mapping:
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("[User]");
Id(x => x.UserID);
Map(x => x.Type).CustomType<int>();
Map(x => x.Email);
}
}
public class CompanyMap : ClassMap<Company>
{
public CompanyMap()
{
Table("Company");
Id(x => x.UserID);
Map(x => x.Name);
}
}
public class StudentMap: ClassMap<Student>
{
public StudentMap()
{
Table("Student");
Id(x => x.UserID);
Map(x => x.Firstname);
Map(x => x.Lastname);
}
}
There are few really good articles on the internet about
Fluent mapping
and NHibernate inheritance. One of them is aboutmapping-by-code
, but it provides detailed explanation about theFluent mapping
as well (just scroll down)Mapping-by-Code - inheritance by Adam Bar
small extract related to your scenario
Another really good and comprehensive article:
Inheritance mapping strategies in Fluent Nhibernate by Igor Ignatov
BUT, I would suggest:
Please, do read this:
Composition over inheritance
small cite:
NHibernate is really tremendous tool, supporting almost any kind of our wish... but it still should not mean, that we should use it.