Recently I was working on a project that required a categorization option. I wanted the user to have the option to create categories and as many subcategories as they wanted. To realize this I created a category model that was self referencing:
1 2 3 4 5 6 7 8 9 |
public class Category { public int Id { get; set; } public string Name { get; set; } public int? ParentId { get; set; } [ForeignKey("ParentId")] public virtual Category Parent { get; set; } } |
It’s important that you don’t forget the Foreignkey data annotation because otherwise you will get an error like this:
Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
Further make sure that ParentId is nullable because it makes no sense if every category has a parent if it was even possible.
Alternative
Instead of using data annotations you can also use Fluent API to create a self referencing model. When you choose for this approach add the following code to your DbContext:
1 2 3 4 5 6 7 8 |
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Category>() .HasOptional(e => e.Parent) .WithMany() .HasForeignKey(m => m.ParentId) .WillCascadeOnDelete(true); // do delete children when parent is deleted; } |
Hi,
How can I implement it in ASP.NET Core 2?
Please visit this link:
https://stackoverflow.com/q/49211561/1817640
Just spent all afternoon trying to figure this out, looked at 100 tutorials and websites – nothing worked until I got here.
Thank you for your simplicity and clarity.
If we ever meet I owe you a pint!
thank a lot man.
do you have any sample in your site?