Most developers prefer Code First style when they use entity framework in their applications. This approach was being primarily used for new applications as it would be difficult to code all the classes for the respective tables when dealing with existing database with lots of tables. But with the advent of Entity framework power tools, you can use Code First approach on existing database even with lots of tables without much effort.
You can download and install Entity Framework Power Tools Beta 4 from the following link
Once you have installed Entity framework power tools, you would get a menu item by name Entity Framework when you right click on your project.
To explain the code first approach on existing databases, I am going to use the popular AdventureWorks (2005 version) database which I have downloaded from following URL.
Note: The reason I am downloading AdventureWorks database of SQL Server 2005 version is that in later versions(2008 and 2012), SQL Server has introduced a data type hierarchyid which is incompatible with Entity Framework. This data type is being used in AdventureWorks database.
After downloading, I have attached the AdventureWorks database in my SQL Server Express as explained below
Attaching AdventureWorks database :
1.Right click on Databases and select Attach
2. Click Add and select the database(mdf file) and click OK
One you have attached AdventureWorks database, you can generate the classes for the corresponding tables available in the database as explained below.
Generating classes for existing database (AdventureWorks in this case):
Right click on the project and select Entity Framework-> Reverse Engineer Code First
Enter your Server name( I am using SQL Server Express edition) and select AdventureWorks database and click OK. Entity framework power tools would generate Entity and Mapping classes in Models folder
I am adding ProductController (to my ASP.MVC 5 application) as scaffold item
Once the controller is added, I access the application through the URL http://localhost:1722/Product/, I get the list of all products available in Products table in AdventureWorks database.
Thus, by using Entity Framework Power Tools, we can use Code First approach on existing databases without any hassles.
Thanks for reading. If you like this article, please subscribe below so that I can send articles straight to your inbox.[mc4wp_form]