This post is about reverse engineering model classes from existing database using Entity Framework Core. This is useful in Database First scenarios than the Code First scenario. In order to scaffold a DbContext from an existing database, you first have to set up project.json file. You need to add reference of Entity Framework tools in the project.json file tools section. For this post I am generating DbContext and model classes from Sqlite Database. So I am using EF Sqlite references as well.
Now you need to run the “dotnet restore” command to restore the packages. Once the packages restored successfully, you can verify the EF tool installation using “dotnet ef” command, which will display EF console like this.
You can run all the EF commands similar to previous versions commands. You can find more details about EF migration commands in this post.
To reverse engineer model classes and db context you need to execute the following command, which will generate the classes in the specified output directory.
The “-o” command line argument is for specifing the output directory, “-c” is for specifing the DbContext class name, “-f” is for forcing the class generation, even if the classes exists. And the last “-a” is for using DataAnnotation attributes to configure the model, instead of fluent API. You can find more details about the dbcontext scaffold command using –help option.
Happy Programming :)