How to Configure a Self Referencing Entity in Code First

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:

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.


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. 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!


Leave a Comment.