How can I create a parent/child relationship with the same object with AutoPersistenceModel
I have the following class in my project
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开发者_如何学Go<ProductCategory> Categories { get; set; }
}
my database table is as follows:
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
)
I am trying to allow for a Category to be a child of another, and obviously, the parent could have multiple categories.
I am having troubles getting my AutoPersistenceModel to work. This is what I have for my mapping.
.ForTypesThatDeriveFrom(map =>
{
map.HasMany(productCategory => productCategory.ProductCategories).WithForeignKeyConstraintName("ProductCategory_id");
map.HasOne(productCategory => productCategory.ParentCategory).WithForeignKey("ProductCategory_id");
});
I've tried a few different things that just haven't worked for me. It seems to map the HasMany correctly. But the HasOne ends up being itself, rather than the correct parent entity, or nothing (null), when the ParentCategory_id is null in the database
Anthony, try changing the has one to this.
map.References(productCategory => productCategory.ParentCategory).WithColumns("ProductCategory_id").FetchType.Select();
The has one is a one-to-one relationship you're looking to reference another class as a parent.
We do something similar in one of our projects, this is the convention we use:
public class ProductCategoryReferencingConvention : IHasManyToManyConvention
{
public bool Accept(IManyToManyPart target)
{
return target.EntityType == typeof (ProductCategory);
}
public void Apply(IManyToManyPart target)
{
target.WithParentKeyColumn("ProductCategory_id");
}
}
精彩评论