Query Types in EF Core

If you have been using Entity Framework 6.x or EF Core, then you are already familiar with Entities and its usage.

Query Types is a new addition to EF Core 2.1 which you can refer to Entities as its cousin.

What are some of the Use Cases

  • Is used when working with entities with no key propertie(s) defined, may it be a Table, Stored Procedure or a View
  • Is used when mapping to queries specified in the model
  • Is used for ad hoc queries where changes are not tracked in DbContext.Β In other words, queries that are strictly read-only

So let’s get Started

First let’s define the two POCO classes. Each of these classes below maps to the tables in the database.

public class BaseAggr
    {
        public long BaseAggrId { get; set; }
        [Display(Name = "Portfolio ID")]
        public string PortfolioId { get; set; }

        [Display(Name = "Scenario ID")]
        public long? ScenarioId { get; set; }

        [Display(Name = "Sum Pnl")]
        public double? SumPnl { get; set; }

        [Display(Name = "Business Date")]
        [DataType(DataType.Date)]
        public DateTime? BusinessDate { get; set; }
    }
    public class WhatIfAggr
    {
        public long WhatifAggrId { get; set; }

        [Display(Name="Portfolio ID")]
        public string PortfolioId { get; set; }

        [Display(Name ="Scenario ID")]
        public long? ScenarioId { get; set; }

        [Display(Name ="Sum PnL")]
        public double? SumPnl { get; set; }

        [Display(Name ="Business Date")]
        [DataType(DataType.Date)]
        public DateTime? BusinessDate { get; set; }
    }

Next, let’s create a database view. As you can tell from the query below that it’s using Common Table Expression to form a result set.

CREATE OR ALTER VIEW [dbo].[vwVarByPortfolios] AS
SELECT * FROM 
(SELECT portfolio_id, scenario_id as scenario_id, sum_pnl as var_pnl 
	FROM (SELECT portfolio_id,scenario_id, sum_pnl, RANK() OVER (PARTITION BY portfolio_id ORDER BY sum_pnl DESC) AS pnl_rank FROM base_aggr) AS Agg
	WHERE pnl_rank = 98
) AS A	INNER JOIN
	
(SELECT portfolio_id AS wi_portfolio_id, scenario_id AS wi_scenario_id, sum_pnl AS wi_var_pnl 
	FROM (SELECT portfolio_id,scenario_id, sum_pnl, RANK() OVER (PARTITION BY portfolio_id ORDER BY sum_pnl desc) AS pnl_rank from whatif_aggr) AS Agg
	WHERE pnl_rank = 98
 ) AS X
 ON portfolio_id = wi_portfolio_id;
GO

In addition to the classes above, you would also need a class for Query Type to hold results from the database view like so:

public class PortfolioView
{
public string PortfolioID { get; set; }
public long ScenarioID { get; set; }
public double VarPnl { get; set; }
public string WiPortfolioID { get; set; }
public long WiScenarioID { get; set; }
public double WiVarPnl { get; set; }
}

Next, we will create a DbQuery property in the DbContext class in order for it to be recognized as a query type.

public DbQuery PortfolioView { get; private set; }

Next, we will write a fluent API in DbConext’s OnModelCreating method to map the view to the Query Type i.e. vwVarByPortfolios. The “ToView” extension method is used to configure the mapping especially when a relational database is being targeted.

modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.PortfolioID).HasColumnName("portfolio_id");

            modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.ScenarioID).HasColumnName("scenario_id");

            modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.VarPnl).HasColumnName("var_pnl");

            modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.WiPortfolioID).HasColumnName("wi_portfolio_id");

            modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.WiScenarioID).HasColumnName("wi_scenario_id");

            modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.WiVarPnl).HasColumnName("wi_var_pnl");

Please note, DbQuery does not require a primary key to be defined unlike its DbSet<T> counterpart. The Id’s are being used here just because they are needed.

What you cannot Do:

Couple things worth noting is that in this version i.e. EF Core 2.2, EF Core does not allow Views to be created in the database when migrations are run. Conversely, you cannot reverse engineer views yet. This will most likely be available in the future version of EF Core i.e. 3.0. Here’s the EF Core Roadmap in case you wish you know further.

Lastly, you can query the database view in your console app or a Web App, although in this case, the latter is being used along with Razor Pages.

 public class PortfolioModel : PageModel
    {
        private readonly DataAggr.Models.DataAggrContext _context;

        public PortfolioModel(DataAggrContext context)
        {
            _context = context;
        }

        [BindProperty]
        public IList PortfolioView { get; set; }

        public async Task OnGetAsync()
        {
            PortfolioView = await _context.Query()
                .ToListAsync();
        }
    }

A quick snapshot of the output of the View from inside SQL Management Studio.

Output on a Razor Page in ASP.NET Core.

Hope you found the article useful!

About Obi Oberoi

I am Technology Aficionado who has a passion for learning, speaking, blogging and hanging out with geeks and like minded people!
This entry was posted in .NET, ORM. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.