Create A Database View Using The Entity Framework (EF) Code First Approach

Introduction

 
There are several situations where your applications may need to display data by combining two or more tables, sometimes even more than 7-8 tables. In such a scenario, using Entity framework may result in a slow performance because we need to process by selecting data from a table, then run a loop for other tables.
 
However, the database itself has many features to handle the performance in these cases, such as stored procedures or creating views that are most recommended and result in better performance. This blog will show how to how to overcome the problems by creating a view in Entity framework.
 
Option 1
 
Create a view combining multiple tables in the database manually and subsequently add an entity for the view. Finally, we can add ignore for the entity OnmodelCreating Entity builder, as shown below.
 
Sample Code
  1. protected override void OnModelCreating(ModelBuilder modelBuilder)  
  2. {  
  3.   if (IsMigration)  
  4.     modelBuilder.Ignore<ViewEntityName>();  
  5.  ...  
  6. }  
Option 2
 
Alternatively, you can create an extension or property for handling views in the database. In this option, we can create a view manually in the database then add an extension or property.
 
Sample Code
  1. //Property  
  2. class DBContext  
  3. {  
  4.     public IQueryable<YourView> YourView   
  5.     {  
  6.         get  
  7.         {  
  8.             return this.Database.SqlQuery<YourView>("select * from dbo.ViewName");  
  9.         }  
  10.     }  
  11. }  
Extension
  1. static class DbContextExtensions  
  2. {  
  3.     public static IQueryable<ViewNameModel>(this DbContext context)  
  4.     {  
  5.         return context.Database.SqlQuery<ViewNameModel>("select * from dbo.ViewName");  
  6.     }  
  7. }  
There are some other alternative methods as well, however, I prefer these options, as they are easy to implement.
 
Hence, these were some quick ways to implement database views in the Entity framework code first approach.