Code First Approach Using Entity Framework

In Entity Framework Code First approach, you do not have to create the database for your application. You just have to add classes to your web application and the database will be generated automatically.

Follow the steps given below to create a web application with Code First approach.

  1. Open Visual Studio and add a new project.
  2. Select WebàASP.NET Web Application and then name it as CodeFirstDemo.



  3. In the next Window select from the given templates. Select MVC template and click OK.



  4. Now, in your Solution Explorer, right click the Models folder and add a .cs class in it and name the class as “Employee”.



  5. Add the properties given below to your class.


  6. Right click on Models folder and add a .cs class. Name it as EmployeeDbContext (this class will generate the database) and add the data given below on it.


  7. Now, right click on Controllers folder and add an empty Controller, name it EmployeeController and add the data given below in it.



  8. Now, rebuild the solution. Right click on “ActionResult Create” and add a View, as shown below.



  9. Now, your “Create View” is generated. Run it in the Browser and check it


  10. Now, add another ActionResult method into your Controller, as shown below and then create its view by following the previous procedure. 


    Add View, as shown below.



  11. Now, run your Application and enter the data to your Create View and click on Create button, based on which the data will be automatically saved to the database and will be shown on Index View.
Ebook Download
View all
Learn
View all