如何使用AutoPersistenceModel与同一对象创建父/子关系

时间:2010-02-11 04:00:46

标签: fluent-nhibernate parent-child

我的项目中有以下课程


public class ProductCategory
{
  public virtual Guid Id { get; set; }
  public virtual string UrlSlug { get; set; }
  public virtual string Title { get; set; }
  public virtual bool IsActive { get; set; }
  public virtual IList<Product> Products { get; set; }
  public virtual ProductCategory Parent { get; set; }
  public virtual IList<ProductCategory> Categories { get; set; }
}

我的数据库表如下:


CREATE TABLE [dbo].[ProductCategory](
  [Id] [uniqueidentifier] NOT NULL,
  [UrlSlug] [nvarchar](255) NULL,
  [Title] [nvarchar](255) NULL,
  [IsActive] [bit] NULL,
  [ProductCategory_id] [uniqueidentifier] NULL -- this is the parent category id
)

我试图允许一个类别成为另一个类别的孩子,显然,父母可以有多个类别。

我遇到麻烦让我的AutoPersistenceModel工作。这就是我的映射。


.ForTypesThatDeriveFrom(map =>
{
  map.HasMany(productCategory => productCategory.ProductCategories).WithForeignKeyConstraintName("ProductCategory_id");
  map.HasOne(productCategory => productCategory.ParentCategory).WithForeignKey("ProductCategory_id");
});

我尝试了一些对我不起作用的不同事情。它似乎正确地映射了HasMany。但是当数据库中的ParentCategory_id为空时,HasOne最终成为自身,而不是正确的父实体,或者什么都不是(null)

2 个答案:

答案 0 :(得分:2)

安东尼,试着改变一个人。

map.References(productCategory => productCategory.ParentCategory).WithColumns("ProductCategory_id").FetchType.Select();

有一个是你想要引用另一个类作为父母的一对一关系。

答案 1 :(得分:1)

我们在其中一个项目中做了类似的事情,这是我们使用的惯例:

public class ProductCategoryReferencingConvention : IHasManyToManyConvention
    {
        public bool Accept(IManyToManyPart target)
        {
            return target.EntityType == typeof (ProductCategory);
        }

        public void Apply(IManyToManyPart target)
        {
            target.WithParentKeyColumn("ProductCategory_id");
        }

    }