2010-02-11 30 views
4

相同對象的父/子關係我有下面的類我怎麼能在我的項目創建與AutoPersistenceModel


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最終成爲它自己而不是正確的父實體,或者什麼也不是(空)。

回答

2

安東尼,嘗試改變有一個這個。

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

的有一個是你正在尋找引用另一個類作爲父母一比一的關係。

1

我們在其中一個項目中做了類似的事情,這是我們使用的約定:

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

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

    }