Working with Database View in Entity Framework 6 DB-First Approach

Here, we will see how to query the database views using Entity Framework 6 Dabase-First approach.

You can use views the same way as you can use tables. So first of all you have to add database views to EDM. It will treat the view as an entity. So you can work with it the same way as normal entities are worked with, except for the CUD (Create, Update, Delete) operation.

We already have a view View_StudentCourse in our database which we want to execute and read data from it using EF 6.

To read data from a db view, first we need to add it in our EDM (Entity Data Model). This you can add while creating a new EDM or updating an existing EDM. Let's update an existing EDM and add a db view View_StudentCourse. (Learn to create a new EDM.)

To update an EDM, right click on the designer and click Update Model From Database.. from the context menu. This will open an update wizard, as shown below. Now, expand the Views node and select an appropriate views. Here, we will select View_StudentCourse view and click Finish button.

db view in Entity Framework

This will add a new entity as a view name in the EDM designer.

db view in Entity Framework

So now you can execute the View_studentCourse using an instance of the DbContext, as shown below.

using (var context = new SchoolDBEntities())
{
    var studentAndCourseList = context.View_StudentCourse.ToList();
    
    foreach (var item in studentAndCourseList)
    {
        Console.WriteLine($"Student: {item.StudentName} Course: {item.CourseName}"); 
    }
}

So in this way you can work with database view using Entity Framework 6.x.