如何使用FluentNHibernate上的EntityBase类映射派生类

时间:2012-10-12 10:03:59

标签: nhibernate fluent

我有一个FluentNHibernate的EntityBase类:

public abstract class EntityBase<T>
{
    public EntityBase()
    {

    }

    public static T GetById(int id)
    {
        return (T)Hibernate.Session.Get<T>(id);
    }
    public virtual void Save()
    {
        using (var transaction = Hibernate.Session.BeginTransaction())
        {
            Hibernate.Session.SaveOrUpdate(this);
            transaction.Commit();
        }
    }
    public static IList<T> List()
    {
        return Hibernate.Session.CreateCriteria(typeof(T)).List<T>();
    }
    public static IList<T> ListTop(int i)
    {
        return Hibernate.Session.CreateCriteria(typeof(T)).SetMaxResults(i).List<T>();
    }
    public virtual void Delete()
    {
        using (var transaction = Hibernate.Session.BeginTransaction())
        {
            Hibernate.Session.Delete(this);
            transaction.Commit();
        }
    }
}

我有一个基本成员类也是数据库中的表:

abstract public class BaseMember:EntityBase<BaseMember>
{
    public virtual int Id { get; set; }
    public virtual string Email { get; set; }
    public virtual string Password { get; set; }
    public virtual string RecordDate { get; protected set; }

    public BaseMember()
    {

    }
}

我有另一个派生自BaseMember类的成员类:

public class IndividualMember : BaseMember
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string PhoneNumber { get; set; }
    public virtual string MobilePhoneNumber { get; set; }
    public virtual DateTime BirthDate { get; set; }
    public virtual bool Gender { get; set; }
    public virtual string ProfileImage { get; set; }
    public virtual string AddressDefinition { get; set; }
    public virtual string ZipCode { get; set; }
    public virtual DateTime RecordDate { get; set; }

    public IndividualMember()
    {

    }
}

如何在db?

中使用BaseMember和IndividualMember表映射这些类

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

Fluent NHibernate中有不同类型的继承映射策略。 您可以将SubclassMap映射用于派生类。

策略:Table-per-class-hierarchy,Table-per-subclass和Table Per Concrete Class。

对于table-per-class-hierarchy策略,您只需指定discriminator列。

更多参考:

http://www.codeproject.com/Articles/232034/Inheritance-mapping-strategies-in-Fluent-Nhibernat https://github.com/jagregory/fluent-nhibernate/wiki/Fluent-mapping#wiki-subclasses