The first EF Core stored procedure call I see in reviews is FromSqlRaw("EXEC dbo.GetOrdersByState '" + state + "'"). It works until someone types TX'; UPDATE dbo.Orders SET Total = 0; -- into the search box. My test zeroed every order.
The fix is FromSql with an interpolated string, which EF Core sends as a real SQL parameter:
var orders = await db.Orders
.FromSql($"EXEC dbo.GetOrdersByState {state}")
.ToListAsync();
I ran every call below on EF Core 10.0.14 against SQL Server, including OUTPUT parameters and the error you get when you add a Where().
Set Up the Sample Database and Stored Procedures
The demo is a .NET 10 console app called W13Sproc with eight US orders and five procedures. If you’re new to DbContext, my EF Core tutorial covers the basics first. Here’s the project file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.14" />
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="10.0.14" />
</ItemGroup>
</Project>
Note: without the second package, the build warned NU1902 and NU1903 about System.Security.Cryptography.Pkcs 9.0.11, which comes in through Microsoft.Data.SqlClient. Pinning 10.0.14 cleared both warnings.
The entity, plus a record for a result that isn’t in the model:
namespace W13Sproc;
public class Order
{
public int Id { get; set; }
public required string Customer { get; set; }
public required string City { get; set; }
public required string State { get; set; }
public DateOnly OrderDate { get; set; }
public decimal Total { get; set; }
}
// Not in the EF model: filled by Database.SqlQuery<T>
public record StateSales(string State, int Orders, decimal Revenue);
The context logs only the executed command when you pass logSql: true, so you can see the SQL EF Core really sends:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
namespace W13Sproc;
public class SalesDb(bool logSql = false) : DbContext
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("Server=.;Database=w13SprocDemo;Trusted_Connection=True;TrustServerCertificate=True");
if (logSql)
options.LogTo(Console.WriteLine, [RelationalEventId.CommandExecuted],
LogLevel.Information, DbContextLoggerOptions.None);
}
protected override void OnModelCreating(ModelBuilder modelBuilder) =>
modelBuilder.Entity<Order>(o =>
{
o.Property(x => x.Customer).HasMaxLength(100);
o.Property(x => x.City).HasMaxLength(60);
o.Property(x => x.State).HasMaxLength(2).IsFixedLength();
o.Property(x => x.Total).HasPrecision(10, 2);
});
}
These are the five procedures. Each one is a raw string literal, run once by the setup code:
namespace W13Sproc;
public static class Procs
{
public static readonly string[] All =
[
"""
CREATE OR ALTER PROCEDURE dbo.GetOrdersByState @State char(2) AS
SET NOCOUNT ON;
SELECT Id, Customer, City, State, OrderDate, Total
FROM dbo.Orders WHERE State = @State ORDER BY OrderDate;
""",
"""
CREATE OR ALTER PROCEDURE dbo.GetSalesByState AS
SET NOCOUNT ON;
SELECT State, COUNT(*) AS Orders, SUM(Total) AS Revenue
FROM dbo.Orders GROUP BY State ORDER BY Revenue DESC;
""",
"""
CREATE OR ALTER PROCEDURE dbo.GetOrderCount @State char(2) AS
SET NOCOUNT ON;
SELECT COUNT(*) AS Value FROM dbo.Orders WHERE State = @State;
""",
"""
CREATE OR ALTER PROCEDURE dbo.ApplyDiscount @State char(2), @Percent decimal(5,2) AS
UPDATE dbo.Orders SET Total = ROUND(Total * (100 - @Percent) / 100, 2)
WHERE State = @State;
""",
"""
CREATE OR ALTER PROCEDURE dbo.AddOrder @Customer nvarchar(100), @City nvarchar(60),
@State char(2), @OrderDate date, @Total decimal(10,2), @NewId int OUTPUT AS
SET NOCOUNT ON;
INSERT dbo.Orders (Customer, City, State, OrderDate, Total)
VALUES (@Customer, @City, @State, @OrderDate, @Total);
SET @NewId = SCOPE_IDENTITY();
"""
];
}
Setup creates the table, reloads the same eight rows and runs every CREATE OR ALTER PROCEDURE. I run it before each demo:
using Microsoft.EntityFrameworkCore;
namespace W13Sproc;
public static class Setup
{
public static async Task RunAsync()
{
using var db = new SalesDb();
await db.Database.EnsureCreatedAsync(); // creates the DB and table on the first run
await db.Database.ExecuteSqlRawAsync("TRUNCATE TABLE dbo.Orders");
db.Orders.AddRange(
new Order { Customer = "Jenna Morales", City = "Austin", State = "TX", OrderDate = new(2026, 10, 6), Total = 642.50m },
new Order { Customer = "Tyler Brooks", City = "Dallas", State = "TX", OrderDate = new(2026, 10, 14), Total = 318.00m },
new Order { Customer = "Grace Whitfield", City = "Houston", State = "TX", OrderDate = new(2026, 11, 2), Total = 1125.75m },
new Order { Customer = "Marcus Reyes", City = "San Diego", State = "CA", OrderDate = new(2026, 10, 9), Total = 489.99m },
new Order { Customer = "Olivia Chen", City = "Sacramento", State = "CA", OrderDate = new(2026, 10, 27), Total = 975.00m },
new Order { Customer = "Derek Lawson", City = "Tampa", State = "FL", OrderDate = new(2026, 10, 18), Total = 254.25m },
new Order { Customer = "Hannah Pierce", City = "Orlando", State = "FL", OrderDate = new(2026, 11, 4), Total = 710.40m },
new Order { Customer = "Caleb Turner", City = "Columbus", State = "OH", OrderDate = new(2026, 10, 22), Total = 399.00m });
await db.SaveChangesAsync();
foreach (string sql in Procs.All)
await db.Database.ExecuteSqlRawAsync(sql);
Console.WriteLine($"{db.Database.GetDbConnection().Database}: {await db.Orders.CountAsync()} orders, {Procs.All.Length} procedures");
}
}
Output:
w13SprocDemo: 8 orders, 5 procedures
In a real project, put the procedures in an EF Core migration instead, so every database gets them. Add an empty migration and call migrationBuilder.Sql:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("""
CREATE OR ALTER PROCEDURE dbo.GetOrdersByState @State char(2) AS
SET NOCOUNT ON;
SELECT Id, Customer, City, State, OrderDate, Total
FROM dbo.Orders WHERE State = @State ORDER BY OrderDate;
""");
}
protected override void Down(MigrationBuilder migrationBuilder) =>
migrationBuilder.Sql("DROP PROCEDURE IF EXISTS dbo.GetOrdersByState;");
Program.cs picks a demo by argument, so dotnet run -- fromsql runs the next example:
using System.Globalization;
using W13Sproc;
CultureInfo.CurrentCulture = new CultureInfo("en-US");
switch (args.FirstOrDefault())
{
case "setup": await Setup.RunAsync(); break;
case "inject": await Injection.RunAsync(); break;
case "fromsql": await BasicFromSql.RunAsync(); break;
case "raw": await RawParams.RunAsync(); break;
case "sqlquery": await SqlQueryDemo.RunAsync(); break;
case "write": await WriteProcs.RunAsync(); break;
case "compose": await ComposeError.RunAsync(); break;
default: Console.WriteLine("Pass setup, inject, fromsql, raw, sqlquery, write or compose."); break;
}
How to Call a Stored Procedure in EF Core with FromSql
Start the query from the DbSet that matches the rows the procedure returns, and put the parameters inside the interpolated string:
using Microsoft.EntityFrameworkCore;
namespace W13Sproc;
public static class BasicFromSql
{
public static async Task RunAsync()
{
using var db = new SalesDb(logSql: true);
string state = "TX";
List<Order> orders = await db.Orders
.FromSql($"EXEC dbo.GetOrdersByState {state}")
.ToListAsync();
foreach (var o in orders)
Console.WriteLine($"{o.OrderDate:MM/dd/yyyy} {o.Customer,-16} {o.City,-8} {o.Total,10:C}");
}
}

Output:
Executed DbCommand (33ms) [Parameters=[p0='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
EXEC dbo.GetOrdersByState @p0
10/06/2026 Jenna Morales Austin $642.50
10/14/2026 Tyler Brooks Dallas $318.00
11/02/2026 Grace Whitfield Houston $1,125.75
The log line is the proof: EF Core sent EXEC dbo.GetOrdersByState @p0, not the text TX. I covered more ways to see the SQL in how to see the SQL EF Core generates.
The rows are tracked Order entities, so you can change one and call SaveChangesAsync. The procedure must return every mapped column, with names that match the column names.
Every call here is async. Sync versions exist (ToList, ExecuteSql), but in web apps stick to the async and await versions so a slow procedure doesn’t block a thread.
FromSql vs FromSqlInterpolated vs FromSqlRaw
All three call the same procedure. The difference is how parameters get in. Same database, three states:
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
namespace W13Sproc;
public static class RawParams
{
public static async Task RunAsync()
{
using var db = new SalesDb();
var state = new SqlParameter("State", "CA");
var ca = await db.Orders.FromSqlRaw("EXEC dbo.GetOrdersByState @State", state).ToListAsync();
Console.WriteLine($"FromSqlRaw + SqlParameter: {ca.Count} CA orders");
var oh = await db.Orders.FromSqlRaw("EXEC dbo.GetOrdersByState {0}", "OH").ToListAsync();
Console.WriteLine($"FromSqlRaw + {{0}} placeholder: {oh.Count} OH order ({oh[0].Customer})");
string fl = "FL";
var florida = await db.Orders.FromSqlInterpolated($"EXEC dbo.GetOrdersByState @State = {fl}").ToListAsync();
Console.WriteLine($"FromSqlInterpolated, named: {florida.Count} FL orders, {florida.Sum(o => o.Total):C}");
}
}
Output:
FromSqlRaw + SqlParameter: 2 CA orders
FromSqlRaw + {0} placeholder: 1 OH order (Caleb Turner)
FromSqlInterpolated, named: 2 FL orders, $964.65
| Method | Parameters | Use it when |
|---|---|---|
FromSql($"...{x}") | Interpolated values become DbParameters | Default choice (EF Core 7 and later) |
FromSqlInterpolated | Same as FromSql | Older code, EF Core 3 to 6 |
FromSqlRaw(sql, params) | Only the {0} placeholders or SqlParameter objects you pass | The SQL text itself is built at run time |
Named parameters (@State = {fl}) help when a procedure has optional parameters. A SqlParameter also lets you set the exact type and size, since a plain string parameter went out with Size = 4000 in the log above.
Why Is FromSqlRaw with String Concatenation Dangerous?
Here’s the intro bug as a full program. The state value is what an attacker would type into a filter box:
using Microsoft.EntityFrameworkCore;
namespace W13Sproc;
public static class Injection
{
public static async Task RunAsync()
{
using var db = new SalesDb();
string state = "TX'; UPDATE dbo.Orders SET Total = 0; --"; // typed into a search box
// DON'T: string concatenation inside FromSqlRaw
var orders = await db.Orders
.FromSqlRaw("EXEC dbo.GetOrdersByState '" + state + "'")
.ToListAsync();
Console.WriteLine($"Rows returned: {orders.Count}");
Console.WriteLine($"Sum of all orders now: {await db.Orders.SumAsync(o => o.Total):C}");
}
}

Output:
Rows returned: 3
Sum of all orders now: $0.00
The quote closed the TX literal, so SQL Server ran the procedure and then the attacker’s UPDATE. Nothing failed, which is what makes this bug so nasty.
The compiler did warn me. EF Core 10 ships an analyzer, and the build printed:
warning EF1003: Method 'FromSqlRaw' inserts concatenated strings directly into the SQL, without any protection against SQL injection. Consider using 'FromSql' instead, which protects against SQL injection, or make sure that the value is sanitized and suppress the warning.
Don’t suppress EF1003 to quiet the build. Switch to FromSql, or pass the value as a SqlParameter like the FromSqlRaw examples above. In a web API, validate the request too, so a bad state code never reaches the database.
Return Unmapped Types and Scalars with EF Core SqlQuery
GetSalesByState returns a summary, not orders, so there’s no DbSet to start from. Database.SqlQuery fills any class or record with a property per column (EF Core 8 and later):
using Microsoft.EntityFrameworkCore;
namespace W13Sproc;
public static class SqlQueryDemo
{
public static async Task RunAsync()
{
using var db = new SalesDb();
List<StateSales> sales = await db.Database
.SqlQuery<StateSales>($"EXEC dbo.GetSalesByState")
.ToListAsync();
foreach (var s in sales)
Console.WriteLine($"{s.State} Orders: {s.Orders} Revenue: {s.Revenue,10:C}");
string state = "TX";
List<int> count = await db.Database
.SqlQuery<int>($"EXEC dbo.GetOrderCount {state}")
.ToListAsync();
Console.WriteLine($"Texas orders (scalar): {count.Single()}");
}
}

Output:
TX Orders: 3 Revenue: $2,086.25
CA Orders: 2 Revenue: $1,464.99
FL Orders: 2 Revenue: $964.65
OH Orders: 1 Revenue: $399.00
Texas orders (scalar): 3
StateSales is a positional C# record, and EF Core matched State, Orders and Revenue by name. Results like this aren’t tracked and can’t have relationships.
For a scalar, name the column Value, as GetOrderCount does. Learn asks for that name when you compose LINQ over the query. The call returned 3.
Run INSERT and UPDATE Procedures with ExecuteSql
Procedures that change data don’t return entity rows, so call them on Database. ExecuteSqlAsync returns the rows affected:
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
namespace W13Sproc;
public static class WriteProcs
{
public static async Task RunAsync()
{
using var db = new SalesDb();
string state = "TX";
decimal percent = 10m;
int rows = await db.Database.ExecuteSqlAsync($"EXEC dbo.ApplyDiscount {state}, {percent}");
Console.WriteLine($"ApplyDiscount: {rows} rows affected");
var newId = new SqlParameter("NewId", SqlDbType.Int) { Direction = ParameterDirection.Output };
var date = new DateOnly(2026, 11, 6);
int added = await db.Database.ExecuteSqlAsync(
$"EXEC dbo.AddOrder {"Ava Sullivan"}, {"Denver"}, {"CO"}, {date}, {845.20m}, {newId} OUTPUT");
Console.WriteLine($"AddOrder: ExecuteSql returned {added}, new order Id = {(int)newId.Value}");
}
}

Output:
ApplyDiscount: 3 rows affected
AddOrder: ExecuteSql returned -1, new order Id = 9
ApplyDiscount took 10% off the three Texas orders. AddOrder returned -1 because it starts with SET NOCOUNT ON, which stops SQL Server from reporting row counts.
I checked the table afterward with sqlcmd:
Id Customer State Total
-- -------- ----- -----
1 Jenna Morales TX 578.25
2 Tyler Brooks TX 286.20
3 Grace Whitfield TX 1013.18
9 Ava Sullivan CO 845.20
Jenna’s $642.50 order is now $578.25, and Ava Sullivan’s Denver order got Id 9.
OUTPUT Parameters with SqlParameter
An OUTPUT value needs a SqlParameter with Direction = ParameterDirection.Output, and the word OUTPUT after it in the SQL. Read .Value after the call finishes. Forget either part and the value stays null.
EF Core LINQ vs Stored Procedures: Which Should You Use?
My verdict: write LINQ by default and call a stored procedure when the logic already lives in the database or LINQ can’t express it well.
| EF Core LINQ | Stored procedure | |
|---|---|---|
| Type checking | Compile time | Column names checked at run time |
| Compose Where / OrderBy / paging | Yes, in SQL | No, only in memory |
| Change tracking | Yes | Yes with FromSql on a DbSet |
| Schema changes | Migrations update the model | You edit the procedure too |
| Good for | CRUD and most queries | Existing DBA-owned logic, heavy reports, bulk updates |
For a typical ASP.NET Core Web API with EF Core, I keep CRUD in LINQ and use procedures for one or two reports. Both run as parameterized SQL, so I don’t pick a procedure for speed alone.
Why Does Where() After a Stored Procedure Call Throw?
EF Core composes LINQ by wrapping your SQL in a subquery, and SQL Server can’t put an EXEC inside a SELECT. Same Texas orders, one filter added:
using Microsoft.EntityFrameworkCore;
namespace W13Sproc;
public static class ComposeError
{
public static async Task RunAsync()
{
using var db = new SalesDb();
string state = "TX";
try
{
var big = await db.Orders.FromSql($"EXEC dbo.GetOrdersByState {state}")
.Where(o => o.Total > 500m).ToListAsync();
}
catch (Exception ex) { Console.WriteLine($"{ex.GetType().Name}: {ex.Message}"); }
// Fix: stop EF Core from composing; the filter runs in C#
var bigOrders = await db.Orders.FromSql($"EXEC dbo.GetOrdersByState {state}")
.AsAsyncEnumerable().Where(o => o.Total > 500m).ToListAsync();
Console.WriteLine($"AsAsyncEnumerable: {bigOrders.Count} TX orders over $500");
}
}

Output:
InvalidOperationException: 'FromSql' or 'SqlQuery' was called with non-composable SQL and with a query composing over it. Consider calling 'AsEnumerable' after the method to perform the composition on the client side.
AsAsyncEnumerable: 2 TX orders over $500
AsAsyncEnumerable() (or AsEnumerable() in sync code) ends the SQL part of the query, so the Where runs as plain LINQ in C# over the returned rows. The ToListAsync after it is the System.Linq.AsyncEnumerable version built into .NET 10.
If you need the filter in SQL, add a parameter to the procedure, or move the query into a view or table-valued function that EF Core can compose over.
Once your procedures work, these help wire them into a real app:
- Dependency injection lifetimes for DbContext
- Pass a CancellationToken to long queries
- Keep connection strings per environment
- All ASP.NET Core tutorials
Frequently Asked Questions
How do I call a stored procedure in EF Core?
Use FromSql on a DbSet when the procedure returns entity rows, for example db.Orders.FromSql($"EXEC dbo.GetOrdersByState {state}"). Use Database.SqlQuery<T> for other result shapes and Database.ExecuteSql for procedures that only change data.
Is FromSql safe from SQL injection?
Yes. Every value in the interpolated string goes to SQL Server as a DbParameter. FromSqlRaw is only safe when you pass values as parameters, never concatenated into the SQL text.
Can I use Where or OrderBy after calling a stored procedure?
Not in the database. SQL Server can’t compose over EXEC, so EF Core throws InvalidOperationException. Call AsAsyncEnumerable() or AsEnumerable() first, then filter in memory.
How do I get an OUTPUT parameter from a stored procedure in EF Core?
Create a SqlParameter with Direction = ParameterDirection.Output, pass it in the SQL followed by OUTPUT, and read its Value after ExecuteSqlAsync returns.
What is the difference between FromSql and SqlQuery in EF Core?
FromSql returns entities from your model and can track them. SqlQuery<T> maps rows to scalars or any unmapped type. Microsoft’s SQL queries in EF Core page covers both.
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…