Recently one of my friends was migrating a project from ASP.Net MVC 5 to ASP.Net core 3.1. One of the challenges he faced is with the Index Attribute in data annotations. The .Net Core is not recognizing the Index attribute. When he copied his class from his MVC 5 project, he got the following error message.
Though the other data annotations accepted by .Net Core, this data attribute “Index” was throwing an exception.
“Index is not an attribute class”
Cool!. Let us dig into the details. You can find the related post on the Entity Framework Github page.
From the page, it is clear now, this is not a bug, the EF Core team didn’t migrate the Index Attribute from the EF 6. So we need to live with this.
Now the question arises, how we are going to add the Indexes to our Tables. The answer is to use the Fluent API in ASP.Net core.
You can refer to the following link on the Microsoft Site to get the details of how to apply the Index to a property.
So the solution is to replace the Index Attribute to the Fluent API, as below.
In real life, you will have many classes, and adding all classes using Fluent API inside OnModelCreating() method will make your code difficult to maintain. The solution is to create a separate class derived from IEntityTypeConfiguration. This will help us define all the related configurations in a single class and then apply the configurations from the OnModelCreating() method.
Let us apply the configuration class for the above. The following is the configuration class.
Once you have the configuration class, you can apply the configuration in the ModelCreating() method as follows.
Happy Coding!
#asp.net #asp.net core 3.1 #.net core #entity framework core #mvc #migration #.net #microsoft