0

我有一个像这样的层次类别表

Id int,
Description varchar(100),
ParentId int,
Ordinal int,
IsActive bit

我想从父级到子级获取所有类别,所以当我打电话时session.get<Category>(id),它已经获取了他们所有的子级。这是我的地图和班级:

class Category
{
    public virtual int Id {get; set;}
    public virtual string Description {get; set;}
    public virtual int ParentId {get; set;}
    public virtual int Ordinal {get; set;}
    public virtual bool IsActive {get; set;}
}

class CategoryMap : ClassMap<Category>
{
    public CategoryMap()
    {
         Table("TB_CATEGORY");
         Id(f => f.Id).GeneratedBy.Native();
         Map(f => f.Description);
         Map(f => f.ParentId);
         Map(f => f.Ordinal);
         Map(f => f.IsActive);
    }
}

我搜索了很多文章,但在使用他们的解决方案时仍然感到困惑,因为他们没有告诉我有关表结构和映射的信息。就像ayende blog中的这个,我认为它是一个很好的解决方案,但我不能很好地遵循它来在我的项目中应用它。有人可以给我一步一步的教程来实现这一点吗?我的映射和类是否正确?

4

1 回答 1

1

使用以下类

class Category
{
    public virtual int Id {get; private set;}
    public virtual string Description {get; set;}
    public virtual Category Parent {get; set;}
    public virtual bool IsActive {get; set;}
    public virtual IList<Category> Children {get; private set;}

    public override bool Euqals(object obj)
    {
        var other = obj as Category;
        return other != null && (Id == 0) ? ReferenceEquals(other, this) : other.Id == Id;
    }

    public override int GetHashCode()
    {
        return Id;
    }
}

class CategoryMap : ClassMap<Category>
{
    public CategoryMap()
    {
         Table("TB_CATEGORY");
         Id(f => f.Id).GeneratedBy.Native();
         Map(f => f.Description);
         References(f => f.Parent).Column("ParentId");
         HasMany(f => f.Children)
             .AsList(i => i.Column("Ordinal"))      // let the list have the correct order of child items
             .KeyColumn("ParentId")
             .Inverse();              // let the reference maintain the association
         Map(f => f.IsActive);
    }
}

然后你可以查询

var categoriesWithChildrenInitialised = session.QueryOver<Category>()
    .Fetch(c => c.Children).Eager
    .List()
于 2013-06-07T12:36:55.047 回答