• How to Access Data Using Entity Framework in MVC

    by  • December 30, 2015 • Microsoft .NET Entity Framework, Microsoft ASP.NET MVC • 0 Comments

    Entity framework is an object relational mapping framework that enables .NET developers to work with the relational Data. By using entity framework, the developer can retrieve and manipulate data as strongly typed objects.

    Now we have a relational database named as”ElSeif” that has table “Staff” and a developer needs to retrieve staff name in his web application. Staff table is shown below;

    staff

    For retrieving data in MVC by using entity framework we have to follow the six steps given below

    1. Install entity framework using nugget package manager
    2. Add databaseContext.cs class file to the Model folder
    3. Add a connection string, to the web.config file.
    4. Map “Staff” model class to the database table, dbo.staff using Table attribute
    5. Make the required changes to Details() action method in controller
    6. Write the SetIniliazer function in in Global.asax file.

    Step 1 : In visual studio, go to tools and select NuGet package manager or Extensions and updates to install entity framework.

    NUGET

    Step 2 : Add databaseContext class file to Model folder. Here database name  is ELSEIF so we will add ELSEIFContext.cs file to Model folder.

    The purpose of ElSEIFContext class is to establish a connection with the database. Here ElSEIFContext class is inherited from DBContext Class.

    Step 3: Add a connection string, to the web.config file.

    Step 4: Map “Staff” model class to the database table, dbo.staff using Table attribute

    Step 5: Make the object of ELSEIFContext class in the Index() action method of staff controller.

    ElSEIFContext class have property staffs which will return the list of staff present in the database through the above code.

    Step 6: Write the SetIniliazer function in in Global.asax file .

    Here SetIniliazer function creates and initialize the database. if it is Existing database don’t need database initializer so It can be turned off by passing the null property in the method.

    So in this way, we access our database in MVC by using entity framework.  Output is given below;

     

    outputlatest

     

     

     




    Namecheap.com

    Leave a Reply