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
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- if (IsMigration)
- modelBuilder.Ignore<ViewEntityName>();
- ...
- }
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
-
- class DBContext
- {
- public IQueryable<YourView> YourView
- {
- get
- {
- return this.Database.SqlQuery<YourView>("select * from dbo.ViewName");
- }
- }
- }
Extension
- static class DbContextExtensions
- {
- public static IQueryable<ViewNameModel>(this DbContext context)
- {
- return context.Database.SqlQuery<ViewNameModel>("select * from dbo.ViewName");
- }
- }
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.