Free / NHibernate Collections of the Same Class

I am new to NHibernate and it is difficult for me to match the following relationships in this class.

public class Category : IAuditable { public virtual int Id { get; set; } public virtual string Name{ get; set; } public virtual Category ParentCategory { get; set; } public virtual IList<Category> SubCategories { get; set; } public Category() { this.Name = string.Empty; this.SubCategories = new List<Category>(); } } 

Class maps (although this is almost a hunch)

 public class CategoryMap : ClassMap<Category> { public CategoryMap() { Id(x => x.Id); Map(x => x.Name); References(x => x.ParentCategory) .Nullable() .Not.LazyLoad(); HasMany(x => x.SubCategories) .Cascade.All(); } } 

Each category can have a parent category, some categories have many subcategories, etc. etc. I can correctly save the category to save (the correct subcategories and the parent category fk exist in the database), but when loaded, it returns itself as the parent category.

I use Fluent to map classes, but if someone can point me in the right direction just for simple NHibernate, which will also work.

+4
source share
2 answers

So, on HasMany(x=>x.SubCategories) you need to add Inverse() to the call chain and also give it the column name, which I assume is “ParentCategoryId”, given the matching parent category, of course, it depends on your agreement also.

If you posted your spreadsheet, I can give you a complete solution.

+2
source

By convention, Fluent NHibernate will treat Category_Id as a foreign key column. It will not define the "ParentCategoryId" column. If you do not rename your column with a link to "Category_Id", you must specify the column name for both parent and child relationships.

For a category without a parent (absolute parent category) whose reference column is zero, it is reasonable to return itself as the parent or zero depending on how NHibernate processes it, since you choose the desired load.

 public class CategoryMap : ClassMap<Category> { public CategoryMap() { Id(x => x.Id); Map(x => x.Name); References(x => x.ParentCategory) .Column("ParentCategoryId") // Many-To-One : parent .Nullable() .Not.LazyLoad(); HasMany(x => x.SubCategories) .Cascade.All().Inverse().KeyColumn("ParentCategoryId"); //One-To-Many : chidren } } 
+4
source

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


All Articles