Simplified Sproc Calls with EF8

2/26/2024

The "What's New in EF Core 8" Microsoft documentation here says the following:

EF7 introduced raw SQL queries returning scalar types. This is enhanced in EF8 to include raw SQL queries returning any mappable CLR type, without including that type in the EF model.

Seeing this, I decided to give it a try in my Quid app in order to simplify my sproc calls. This turns out to be a nice feature; something I'll probably use for all sproc calls going forward.

The sproc

I started with a simple example, my usp_GetFavorites sproc which takes a BankAccountId and returns the favorite Envelopes, which includes only these fields: EnvelopeId, Name, Total.

The (new) .NET code to call it

The first simple step: Create a record which holds the exact values the sproc returns:

record GetFavoritesResult(int EnvelopeId, string Name, decimal Total);

Next in the code where I call the sproc with the EF DB context, I simply put:

    context.Database.OpenConnection();
    var qryResult = context.Database
        .SqlQuery<GetFavoritesResult>
            ($"exec dbo.usp_GetFavorites {bankAccountId}")
        .ToList();
    // Now iterate through qryResult, a list of GetFavoritesResult's

That's all. No need to do any mapping in the EF model, or mapping a return call using DbCommand.ExecuteReader(), followed by reader.GetValue calls. If I change the return values of the sproc, I simply update the GetFavoritesResult record.

That's about as easy as it gets!


Please register or login to add a comment.

Comments (displaying 1 - 1):
No comments yet! Be the first...


  • C#/.NET/Core
  • T-SQL
  • HTML/Javascript/jQuery
  • ASP.NET/MVC
  • .NET Core
  • ADO.NET/EF
  • WPF
  • Xamarin/MAUI
  • Windows 10
  • SQL Server 20xx
  • Android
  • XBox One
  • Skiing
  • Rock Climbing
  • White water kayaking
  • Road Biking