流畅的NHibernate中的分层零对一关系

时间:2013-07-18 16:37:19

标签: c# .net nhibernate orm fluent-nhibernate

我对nHibernate有些陌生,特别流利,我在映射类A扩展类B的关系时遇到了麻烦,但不保证给定A 1}}也是B。这里有一个关于结构到目前为止的概念(并且可以接受建议):

public class User
{
    public virtual Guid Id;
    public virtual string UserName;
    public virtual string HashedPassword;
    //...
}

public class Student : User
{
    public virtual Guid UserId;
    public virtual School School;
    public virtual float GPA;
}

public class Teacher : User
{
    public virtual Guid UserId;
    public virtual School School;
    public virtual string ClassName;
}

所以我想拥有可以使用的TeacherStudent个对象,但我也希望能够跟踪它们以进行成员资格验证(因此User类)。

所以有两个问题:

  1. 这是一种合理的方式来做我想做的事吗?

  2. 如果是这样,如何使用Fluent nHibernate进行映射?

1 个答案:

答案 0 :(得分:1)

选项1

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("Users");

        Id(x => x.Id);

        Map(x => x.Name);
        Map(x => x.HashedPassword);
    }
}
public class StudentMap : SubclassMap<Student>
{
    public StudentMap()
    {
        Table("Students");

        References(x => x.School);
        Map(x => x.GPA);
    }
}
public class TeacherMap : SubclassMap<Teacher>
...

Users (
    Id,        // PK
    Name,
    HashedPassword
)
Students (
    User_Id,        // PK, FK
    School_id,
    Gpa
)

选项2

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("Users");
        DiscriminateSubclassesOnColumn("UserType", "user");

        Id(x => x.Id);

        Map(x => x.Name);
        Map(x => x.HashedPassword);
    }
}
public class StudentMap : SubclassMap<Student>
{
    public StudentMap()
    {
        DiscriminatorValue("student");

        References(x => x.School);
        Map(x => x.GPA);
    }
}
public class TeacherMap : SubclassMap<Teacher>
...

Users (
    Id,        // PK
    UserType,
    Name,
    HashedPassword
    School_id,
    Gpa
    Classname
)

选项3

public abstract class UserMap<TUser> : ClassMap<TUser> where TUser : User
{
    public UserMap()
    {
        Id(x => x.Id);

        Map(x => x.Name);
        Map(x => x.HashedPassword);
    }
}
public class StudentMap : UserMap<Student>
{
    public StudentMap()
    {
        Table("Students");

        References(x => x.School);
        Map(x => x.GPA);
    }
}
public class TeacherMap : UserMap<Teacher>
...

Students (
    Id,        // PK
    Name,
    HashedPassword
    School_id,
    Gpa
)
Teachers (
    Id,        // PK
    Name,
    HashedPassword
    School_id,
    Classname
)