Thursday, November 7, 2019

Database First Approach using Entity Framework In ADO.NET


Database First Approach:

Database first approach creates the Entity Framework from an existing database. It creates model codes from the database.

First Create new project in Visual studio 2019

    1.  Right Click on Solution Explore -> Add -> New Projects -> Select Asp.Net Web Application(.Net Framework) using C# code ->Next ->Project Name(DatabaseFirstApproach) ->Create

    2. Select a template -> Empty -> Check MVC -> Ok.

Project is created with MVC folder.



Now, you must add Entity Framework into your project so,

   1.  Right click on Models folder -> Add -> New Item -> Visual C# -> Data -> ADO.NET Entity data Model -> Name(EmployeeModel) -> Add


2.  Entity Data Model Wizard dialog.

Select EF Designer from the database -> Next -> New Connection


Enter your Server name-> Choose your authentication. I am using SQL Server authentication. Thus, we need to provide the user name and password-> Select your database-> Test Connection-> OK.


It includes the sensitive data in the connection string->next->Choose version of Entity Framework.


Include database objects to your model like below -> Finish.


Visual Studio will generate a database diagram for the table like below.



Incase you want to select more tablesthen right click on above page(EmployeeModel.edmx [diagram]) -> Update Model from Database.

Now, you have an Entity Data Model files in your Model folder with all supported files. The screen given above diagram, its shows the auto generated entities files like EmployeeModel.Context.cs. 

EmployeeModel.Context.cs in this class DbContext and DbSet are the ones that we need to establish a link between the model and database.

EmployeeModel.cs class is one where you will see all the properties.

Now Build the application then add controller in Controller folder.

Right Click on Controller folder -> Add ->Controller -> MVC5 Controller with views, using Entity Framework -> Add 


Now, display Add Controller template like below


when you select the model class and Data context class and check all checkboxes under views and click add.

Its automatically added all curd operations in controller and added all views like create, Delete, Details, Edit and Index.






No comments:

Post a Comment