NHibernate ByCode中的分层实体父键

时间:2012-01-23 04:35:20

标签: nhibernate

使用NHibernate 3.2 ByCode配置,我试图映射以下层次结构实体:

public class BusinessType
{
    public virtual Guid BusinessTypeId { get; set; }
    public virtual Guid? ParentBusinessTypeId { get; set; }
    public virtual String BusinessTypeName { get; set; }
    public virtual ICollection<BusinessType> Children { get; set; }
}

使用此ClassMapping:

public class BusinessTypeMapper : ClassMapping<BusinessType>
{
    public BusinessTypeMapper()
    {
        Id(x => x.BusinessTypeId, x => x.Type(new GuidType()));
        Property(x => x.ParentBusinessTypeId, x => x.Type(new GuidType()));
        Property(x => x.BusinessTypeName);
        Set(x => x.Children,
            cm =>
                {
                    // This works, but there is an ugly string in here
                    cm.Key(y => y.Column("ParentBusinessTypeId"));
                    cm.Inverse(true);
                    cm.OrderBy(bt => bt.BusinessTypeName);
                    cm.Lazy(CollectionLazy.NoLazy);
                },
            m => m.OneToMany());
    }
}

这很好用,但我宁愿能够使用lambda指定关系的键,以便重构有效。这似乎可用,如下:

public class BusinessTypeMapper : ClassMapping<BusinessType>
{
    public BusinessTypeMapper()
    {
        Id(x => x.BusinessTypeId, x => x.Type(new GuidType()));
        Property(x => x.ParentBusinessTypeId, x => x.Type(new GuidType()));
        Property(x => x.BusinessTypeName);
        Set(x => x.Children,
            cm =>
                {
                    // This compiles and runs, but generates some other column
                    cm.Key(y => y.PropertyRef(bt => bt.ParentBusinessTypeId));
                    cm.Inverse(true);
                    cm.OrderBy(bt => bt.BusinessTypeName);
                    cm.Lazy(CollectionLazy.NoLazy);
                },
            m => m.OneToMany());
    }
}

问题是这导致NHibernate生成一个名为businesstype_key的列,忽略已经配置的ParentBusinessTypeId。有没有办法让NHibernate使用lambda来指定关系,而不是字符串?

1 个答案:

答案 0 :(得分:1)

  

我从不需要从孩子到父母,只有父母   给孩子们,所以我认为没必要

然后完全删除public virtual Guid? ParentBusinessTypeId { get; set; }。然后NH将只创建“businesstype_key”(约定)而不创建“ParentBusinessTypeId”。如果您想更改它,则必须使用cm.Key(y => y.Column("yourpreferredColumnName"));

指定首选列名