Entity Framework 4.1 Getting Self-Reflection Data

I use Entity Framework 4.1 and ASP.NET MVC 3 code first, and I'm struggling to set up my link correctly. I have a category class. He must refer to himself. A category can be a parent category when the ParentCategoryId in the table is NULL. If a category has a ParentCategoryId value with a value, it means that it belongs to the parent category.

I followed this article in the code draft.

Here is my Category class:

public class Category { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public string MetaKeywords { get; set; } public string MetaDescription { get; set; } public bool IsActive { get; set; } public virtual Category ParentCategory { get; set; } public int? ParentCategoryId { get; set; } } 

My context class:

 public class PbeContext : DbContext { public DbSet<Category> Categories { get; set; } protected override void OnModelCreating(DbModelBuilder dbModelBuilder) { dbModelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); dbModelBuilder.Entity<Category>() .HasOptional(c => c.ParentCategory) .WithMany() .HasForeignKey(p => p.ParentCategoryId); } } 

Not sure if the above is correct?

Can someone please help me get this right? I need that when requesting a category by id, it should return the parent category (only loaded if necessary). It should also load any child categories (only if necessary). I have not yet added a list to the category class for child categories.

What do the above tasks look like to get a category with a parent category and child categories?

EDIT

This is how I extract my category:

 public Category GetById(int id) { return db .Categories .Find(id); } 

Since the ParentCategory link may be null, how do I display this in the view? I have the following:

 @Model.ParentCategory.Name 

.. but will it not give an error if the category does not have a parent category associated with it? How to display it in a view?

+6
source share
1 answer

If you need to access child categories, you can add a collection property to your model.

 public class Category { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public string MetaKeywords { get; set; } public string MetaDescription { get; set; } public bool IsActive { get; set; } public virtual Category ParentCategory { get; set; } public int? ParentCategoryId { get; set; } public virtual ICollection<Category> ChildCategories{ get; set; } } 

Then you can configure the model as

  dbModelBuilder.Entity<Category>() .HasOptional(c => c.ParentCategory) .WithMany(c => ChildCategories) .HasForeignKey(p => p.ParentCategoryId); 

Edit

You should check if ParentCategory is null or not.

 @if(Model.ParentCategory != null){ <div>@Model.ParentCategory.Name</div> } 
+7
source

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


All Articles