How to create parent-child relationships with the same object using the AutoPersistenceModel function

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<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 categories to be a child of another, and obviously a parent can have multiple categories.

I'm having problems getting my AutoPersistenceModel to work. This is what I have for my display.

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

I tried several different things that just didn't work for me. HasMany seems to display correctly. But HasOne turns out to be itself, and not the correct parent or nothing (null) when ParentCategory_id is null in the database

+4
source share
2 answers

Anthony, try changing it to this.

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

The relationship you are looking for to refer to another class as a parent.

+2
source

We are doing something similar in one of our projects, this is the agreement 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"); } } 
+1
source

Source: https://habr.com/ru/post/1300950/


All Articles