<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/" >

<channel>
	<title>AspDotnetHelp.com</title>
	<atom:link href="https://aspdotnethelp.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://aspdotnethelp.com</link>
	<description>Asp.Net and C#.Net Tutorials</description>
	<lastBuildDate>Sun, 08 Nov 2026 03:17:11 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://aspdotnethelp.com/wp-content/uploads/2023/08/aspdotnethelp-favicon-150x150.png</url>
	<title>AspDotnetHelp.com</title>
	<link>https://aspdotnethelp.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Call a Stored Procedure in EF Core (FromSql, SqlQuery, ExecuteSql)</title>
		<link>https://aspdotnethelp.com/call-stored-procedure-ef-core/</link>
		
		<dc:creator><![CDATA[Bijay Kumar]]></dc:creator>
		<pubDate>Wed, 02 Dec 2026 21:20:00 +0000</pubDate>
				<category><![CDATA[ASP.NET Core]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=3097</guid>

					<description><![CDATA[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 ... <a title="How to Call a Stored Procedure in EF Core (FromSql, SqlQuery, ExecuteSql)" class="read-more" href="https://aspdotnethelp.com/call-stored-procedure-ef-core/" aria-label="Read more about How to Call a Stored Procedure in EF Core (FromSql, SqlQuery, ExecuteSql)">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">The first <strong>EF Core stored procedure</strong> call I see in reviews is <code>FromSqlRaw("EXEC dbo.GetOrdersByState '" + state + "'")</code>. It works until someone types <code>TX'; UPDATE dbo.Orders SET Total = 0; --</code> into the search box. My test zeroed every order.</p>



<p class="wp-block-paragraph">The fix is <code>FromSql</code> with an interpolated string, which EF Core sends as a real SQL parameter:</p>



<pre class="wp-block-code"><code>var orders = await db.Orders
    .FromSql($&quot;EXEC dbo.GetOrdersByState {state}&quot;)
    .ToListAsync();</code></pre>



<p class="wp-block-paragraph">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().</p>



<h2 class="wp-block-heading">Set Up the Sample Database and Stored Procedures</h2>



<p class="wp-block-paragraph">The demo is a .NET 10 console app called W13Sproc with eight US orders and five procedures. If you&#8217;re new to <code>DbContext</code>, my <a href="https://aspdotnethelp.com/ef-core-tutorial/">EF Core tutorial</a> covers the basics first. Here&#8217;s the project file:</p>



<pre class="wp-block-code"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;OutputType&gt;Exe&lt;/OutputType&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.SqlServer&quot; Version=&quot;10.0.14&quot; /&gt;
    &lt;PackageReference Include=&quot;System.Security.Cryptography.Pkcs&quot; Version=&quot;10.0.14&quot; /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;</code></pre>



<p class="wp-block-paragraph"><strong>Note:</strong> without the second package, the build warned NU1902 and NU1903 about <code>System.Security.Cryptography.Pkcs</code> 9.0.11, which comes in through <code>Microsoft.Data.SqlClient</code>. Pinning 10.0.14 cleared both warnings.</p>



<p class="wp-block-paragraph">The entity, plus a record for a result that isn&#8217;t in the model:</p>



<pre class="wp-block-code"><code>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&lt;T&gt;
public record StateSales(string State, int Orders, decimal Revenue);</code></pre>



<p class="wp-block-paragraph">The context logs only the executed command when you pass <code>logSql: true</code>, so you can see the SQL EF Core really sends:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;

namespace W13Sproc;

public class SalesDb(bool logSql = false) : DbContext
{
    public DbSet&lt;Order&gt; Orders =&gt; Set&lt;Order&gt;();

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer(&quot;Server=.;Database=w13SprocDemo;Trusted_Connection=True;TrustServerCertificate=True&quot;);
        if (logSql)
            options.LogTo(Console.WriteLine, [RelationalEventId.CommandExecuted],
                LogLevel.Information, DbContextLoggerOptions.None);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder) =&gt;
        modelBuilder.Entity&lt;Order&gt;(o =&gt;
        {
            o.Property(x =&gt; x.Customer).HasMaxLength(100);
            o.Property(x =&gt; x.City).HasMaxLength(60);
            o.Property(x =&gt; x.State).HasMaxLength(2).IsFixedLength();
            o.Property(x =&gt; x.Total).HasPrecision(10, 2);
        });
}</code></pre>



<p class="wp-block-paragraph">These are the five procedures. Each one is a raw string literal, run once by the setup code:</p>



<pre class="wp-block-code"><code>namespace W13Sproc;

public static class Procs
{
    public static readonly string[] All =
    [
        &quot;&quot;&quot;
        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;
        &quot;&quot;&quot;,
        &quot;&quot;&quot;
        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;
        &quot;&quot;&quot;,
        &quot;&quot;&quot;
        CREATE OR ALTER PROCEDURE dbo.GetOrderCount @State char(2) AS
        SET NOCOUNT ON;
        SELECT COUNT(*) AS Value FROM dbo.Orders WHERE State = @State;
        &quot;&quot;&quot;,
        &quot;&quot;&quot;
        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;
        &quot;&quot;&quot;,
        &quot;&quot;&quot;
        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();
        &quot;&quot;&quot;
    ];
}</code></pre>



<p class="wp-block-paragraph">Setup creates the table, reloads the same eight rows and runs every <code>CREATE OR ALTER PROCEDURE</code>. I run it before each demo:</p>



<pre class="wp-block-code"><code>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(&quot;TRUNCATE TABLE dbo.Orders&quot;);

        db.Orders.AddRange(
            new Order { Customer = &quot;Jenna Morales&quot;, City = &quot;Austin&quot;, State = &quot;TX&quot;, OrderDate = new(2026, 10, 6), Total = 642.50m },
            new Order { Customer = &quot;Tyler Brooks&quot;, City = &quot;Dallas&quot;, State = &quot;TX&quot;, OrderDate = new(2026, 10, 14), Total = 318.00m },
            new Order { Customer = &quot;Grace Whitfield&quot;, City = &quot;Houston&quot;, State = &quot;TX&quot;, OrderDate = new(2026, 11, 2), Total = 1125.75m },
            new Order { Customer = &quot;Marcus Reyes&quot;, City = &quot;San Diego&quot;, State = &quot;CA&quot;, OrderDate = new(2026, 10, 9), Total = 489.99m },
            new Order { Customer = &quot;Olivia Chen&quot;, City = &quot;Sacramento&quot;, State = &quot;CA&quot;, OrderDate = new(2026, 10, 27), Total = 975.00m },
            new Order { Customer = &quot;Derek Lawson&quot;, City = &quot;Tampa&quot;, State = &quot;FL&quot;, OrderDate = new(2026, 10, 18), Total = 254.25m },
            new Order { Customer = &quot;Hannah Pierce&quot;, City = &quot;Orlando&quot;, State = &quot;FL&quot;, OrderDate = new(2026, 11, 4), Total = 710.40m },
            new Order { Customer = &quot;Caleb Turner&quot;, City = &quot;Columbus&quot;, State = &quot;OH&quot;, OrderDate = new(2026, 10, 22), Total = 399.00m });
        await db.SaveChangesAsync();

        foreach (string sql in Procs.All)
            await db.Database.ExecuteSqlRawAsync(sql);

        Console.WriteLine($&quot;{db.Database.GetDbConnection().Database}: {await db.Orders.CountAsync()} orders, {Procs.All.Length} procedures&quot;);
    }
}</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>w13SprocDemo: 8 orders, 5 procedures</code></pre>



<p class="wp-block-paragraph">In a real project, put the procedures in an <a href="https://aspdotnethelp.com/ef-core-migrations/">EF Core migration</a> instead, so every database gets them. Add an empty migration and call <code>migrationBuilder.Sql</code>:</p>



<pre class="wp-block-code"><code>protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.Sql(&quot;&quot;&quot;
        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;
        &quot;&quot;&quot;);
}

protected override void Down(MigrationBuilder migrationBuilder) =&gt;
    migrationBuilder.Sql(&quot;DROP PROCEDURE IF EXISTS dbo.GetOrdersByState;&quot;);</code></pre>



<p class="wp-block-paragraph"><code>Program.cs</code> picks a demo by argument, so <code>dotnet run -- fromsql</code> runs the next example:</p>



<pre class="wp-block-code"><code>using System.Globalization;
using W13Sproc;

CultureInfo.CurrentCulture = new CultureInfo(&quot;en-US&quot;);

switch (args.FirstOrDefault())
{
    case &quot;setup&quot;: await Setup.RunAsync(); break;
    case &quot;inject&quot;: await Injection.RunAsync(); break;
    case &quot;fromsql&quot;: await BasicFromSql.RunAsync(); break;
    case &quot;raw&quot;: await RawParams.RunAsync(); break;
    case &quot;sqlquery&quot;: await SqlQueryDemo.RunAsync(); break;
    case &quot;write&quot;: await WriteProcs.RunAsync(); break;
    case &quot;compose&quot;: await ComposeError.RunAsync(); break;
    default: Console.WriteLine(&quot;Pass setup, inject, fromsql, raw, sqlquery, write or compose.&quot;); break;
}</code></pre>



<h2 class="wp-block-heading">How to Call a Stored Procedure in EF Core with FromSql</h2>



<p class="wp-block-paragraph">Start the query from the <code>DbSet</code> that matches the rows the procedure returns, and put the parameters inside the interpolated string:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;

namespace W13Sproc;

public static class BasicFromSql
{
    public static async Task RunAsync()
    {
        using var db = new SalesDb(logSql: true);
        string state = &quot;TX&quot;;

        List&lt;Order&gt; orders = await db.Orders
            .FromSql($&quot;EXEC dbo.GetOrdersByState {state}&quot;)
            .ToListAsync();

        foreach (var o in orders)
            Console.WriteLine($&quot;{o.OrderDate:MM/dd/yyyy}  {o.Customer,-16} {o.City,-8} {o.Total,10:C}&quot;);
    }
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="1384" height="1092" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-fromsql-call-stored-procedure-logged-sql-parameter.png" alt="EF Core FromSql calling the dbo.GetOrdersByState stored procedure in VS Code, with the logged EXEC dbo.GetOrdersByState @p0 command and three Texas orders" class="wp-image-3202" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-fromsql-call-stored-procedure-logged-sql-parameter.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-fromsql-call-stored-procedure-logged-sql-parameter-300x237.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-fromsql-call-stored-procedure-logged-sql-parameter-1024x808.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-fromsql-call-stored-procedure-logged-sql-parameter-768x606.png 768w" sizes="(max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">FromSql turned {state} into the parameter @p0 and returned three Texas orders</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>Executed DbCommand (33ms) [Parameters=[p0=&#x27;?&#x27; (Size = 4000)], CommandType=&#x27;Text&#x27;, CommandTimeout=&#x27;30&#x27;]
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</code></pre>



<p class="wp-block-paragraph">The log line is the proof: EF Core sent <code>EXEC dbo.GetOrdersByState @p0</code>, not the text TX. I covered more ways to see the SQL in <a href="https://aspdotnethelp.com/ef-core-see-generated-sql/">how to see the SQL EF Core generates</a>.</p>



<p class="wp-block-paragraph">The rows are tracked <code>Order</code> entities, so you can change one and call <code>SaveChangesAsync</code>. The procedure must return every mapped column, with names that match the column names.</p>



<p class="wp-block-paragraph">Every call here is async. Sync versions exist (<code>ToList</code>, <code>ExecuteSql</code>), but in web apps stick to the <a href="https://aspdotnethelp.com/async-await-in-csharp/">async and await</a> versions so a slow procedure doesn&#8217;t block a thread.</p>



<h2 class="wp-block-heading">FromSql vs FromSqlInterpolated vs FromSqlRaw</h2>



<p class="wp-block-paragraph">All three call the same procedure. The difference is how parameters get in. Same database, three states:</p>



<pre class="wp-block-code"><code>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(&quot;State&quot;, &quot;CA&quot;);
        var ca = await db.Orders.FromSqlRaw(&quot;EXEC dbo.GetOrdersByState @State&quot;, state).ToListAsync();
        Console.WriteLine($&quot;FromSqlRaw + SqlParameter: {ca.Count} CA orders&quot;);

        var oh = await db.Orders.FromSqlRaw(&quot;EXEC dbo.GetOrdersByState {0}&quot;, &quot;OH&quot;).ToListAsync();
        Console.WriteLine($&quot;FromSqlRaw + {{0}} placeholder: {oh.Count} OH order ({oh[0].Customer})&quot;);

        string fl = &quot;FL&quot;;
        var florida = await db.Orders.FromSqlInterpolated($&quot;EXEC dbo.GetOrdersByState @State = {fl}&quot;).ToListAsync();
        Console.WriteLine($&quot;FromSqlInterpolated, named: {florida.Count} FL orders, {florida.Sum(o =&gt; o.Total):C}&quot;);
    }
}</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>FromSqlRaw + SqlParameter: 2 CA orders
FromSqlRaw + {0} placeholder: 1 OH order (Caleb Turner)
FromSqlInterpolated, named: 2 FL orders, $964.65</code></pre>



<figure class="wp-block-table"><table><thead><tr><th>Method</th><th>Parameters</th><th>Use it when</th></tr></thead><tbody><tr><td><code>FromSql($&quot;...{x}&quot;)</code></td><td>Interpolated values become DbParameters</td><td>Default choice (EF Core 7 and later)</td></tr><tr><td><code>FromSqlInterpolated</code></td><td>Same as FromSql</td><td>Older code, EF Core 3 to 6</td></tr><tr><td><code>FromSqlRaw(sql, params)</code></td><td>Only the {0} placeholders or SqlParameter objects you pass</td><td>The SQL text itself is built at run time</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Named parameters (<code>@State = {fl}</code>) help when a procedure has optional parameters. A <code>SqlParameter</code> also lets you set the exact type and size, since a plain string parameter went out with <code>Size = 4000</code> in the log above.</p>



<h2 class="wp-block-heading">Why Is FromSqlRaw with String Concatenation Dangerous?</h2>



<p class="wp-block-paragraph">Here&#8217;s the intro bug as a full program. The state value is what an attacker would type into a filter box:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;

namespace W13Sproc;

public static class Injection
{
    public static async Task RunAsync()
    {
        using var db = new SalesDb();
        string state = &quot;TX&#x27;; UPDATE dbo.Orders SET Total = 0; --&quot;;  // typed into a search box

        // DON&#x27;T: string concatenation inside FromSqlRaw
        var orders = await db.Orders
            .FromSqlRaw(&quot;EXEC dbo.GetOrdersByState &#x27;&quot; + state + &quot;&#x27;&quot;)
            .ToListAsync();

        Console.WriteLine($&quot;Rows returned: {orders.Count}&quot;);
        Console.WriteLine($&quot;Sum of all orders now: {await db.Orders.SumAsync(o =&gt; o.Total):C}&quot;);
    }
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="1384" height="1092" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-fromsqlraw-string-concatenation-sql-injection-stored-procedure.png" alt="SQL injection through EF Core FromSqlRaw string concatenation in VS Code: the EXEC returns 3 rows and the injected UPDATE sets every order total to $0.00" class="wp-image-3203" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-fromsqlraw-string-concatenation-sql-injection-stored-procedure.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-fromsqlraw-string-concatenation-sql-injection-stored-procedure-300x237.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-fromsqlraw-string-concatenation-sql-injection-stored-procedure-1024x808.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-fromsqlraw-string-concatenation-sql-injection-stored-procedure-768x606.png 768w" sizes="(max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">The concatenated EXEC still returned 3 rows, but the injected UPDATE zeroed every order</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>Rows returned: 3
Sum of all orders now: $0.00</code></pre>



<p class="wp-block-paragraph">The quote closed the <code>TX</code> literal, so SQL Server ran the procedure and then the attacker&#8217;s <code>UPDATE</code>. Nothing failed, which is what makes this bug so nasty.</p>



<p class="wp-block-paragraph">The compiler did warn me. EF Core 10 ships an analyzer, and the build printed:</p>



<pre class="wp-block-code"><code>warning EF1003: Method &#x27;FromSqlRaw&#x27; inserts concatenated strings directly into the SQL, without any protection against SQL injection. Consider using &#x27;FromSql&#x27; instead, which protects against SQL injection, or make sure that the value is sanitized and suppress the warning.</code></pre>



<p class="wp-block-paragraph">Don&#8217;t suppress EF1003 to quiet the build. Switch to <code>FromSql</code>, or pass the value as a <code>SqlParameter</code> like the <code>FromSqlRaw</code> examples above. In a web API, <a href="https://aspdotnethelp.com/minimal-api-validation-aspnet-core/">validate the request</a> too, so a bad state code never reaches the database.</p>



<h2 class="wp-block-heading">Return Unmapped Types and Scalars with EF Core SqlQuery</h2>



<p class="wp-block-paragraph"><code>GetSalesByState</code> returns a summary, not orders, so there&#8217;s no <code>DbSet</code> to start from. <code>Database.SqlQuery<T></code> fills any class or record with a property per column (EF Core 8 and later):</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;

namespace W13Sproc;

public static class SqlQueryDemo
{
    public static async Task RunAsync()
    {
        using var db = new SalesDb();

        List&lt;StateSales&gt; sales = await db.Database
            .SqlQuery&lt;StateSales&gt;($&quot;EXEC dbo.GetSalesByState&quot;)
            .ToListAsync();
        foreach (var s in sales)
            Console.WriteLine($&quot;{s.State}  Orders: {s.Orders}  Revenue: {s.Revenue,10:C}&quot;);

        string state = &quot;TX&quot;;
        List&lt;int&gt; count = await db.Database
            .SqlQuery&lt;int&gt;($&quot;EXEC dbo.GetOrderCount {state}&quot;)
            .ToListAsync();
        Console.WriteLine($&quot;Texas orders (scalar): {count.Single()}&quot;);
    }
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="1384" height="1092" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-sqlquery-unmapped-type-scalar-stored-procedure.png" alt="EF Core Database.SqlQuery returning a StateSales record per state from a stored procedure, plus a scalar Texas order count, in VS Code" class="wp-image-3204" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-sqlquery-unmapped-type-scalar-stored-procedure.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-sqlquery-unmapped-type-scalar-stored-procedure-300x237.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-sqlquery-unmapped-type-scalar-stored-procedure-1024x808.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-sqlquery-unmapped-type-scalar-stored-procedure-768x606.png 768w" sizes="(max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">SqlQuery<StateSales> mapped the summary rows; SqlQuery<int> read a single value</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>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</code></pre>



<p class="wp-block-paragraph"><code>StateSales</code> is a positional <a href="https://aspdotnethelp.com/csharp-record-vs-class-vs-struct/">C# record</a>, and EF Core matched State, Orders and Revenue by name. Results like this aren&#8217;t tracked and can&#8217;t have relationships.</p>



<p class="wp-block-paragraph">For a scalar, name the column <code>Value</code>, as <code>GetOrderCount</code> does. Learn asks for that name when you compose LINQ over the query. The call returned <code>3</code>.</p>



<h2 class="wp-block-heading">Run INSERT and UPDATE Procedures with ExecuteSql</h2>



<p class="wp-block-paragraph">Procedures that change data don&#8217;t return entity rows, so call them on <code>Database</code>. <code>ExecuteSqlAsync</code> returns the rows affected:</p>



<pre class="wp-block-code"><code>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 = &quot;TX&quot;;
        decimal percent = 10m;
        int rows = await db.Database.ExecuteSqlAsync($&quot;EXEC dbo.ApplyDiscount {state}, {percent}&quot;);
        Console.WriteLine($&quot;ApplyDiscount: {rows} rows affected&quot;);

        var newId = new SqlParameter(&quot;NewId&quot;, SqlDbType.Int) { Direction = ParameterDirection.Output };
        var date = new DateOnly(2026, 11, 6);
        int added = await db.Database.ExecuteSqlAsync(
            $&quot;EXEC dbo.AddOrder {&quot;Ava Sullivan&quot;}, {&quot;Denver&quot;}, {&quot;CO&quot;}, {date}, {845.20m}, {newId} OUTPUT&quot;);
        Console.WriteLine($&quot;AddOrder: ExecuteSql returned {added}, new order Id = {(int)newId.Value}&quot;);
    }
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1092" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-executesql-stored-procedure-output-parameter-rows-affected.png" alt="EF Core ExecuteSqlAsync calling the ApplyDiscount and AddOrder stored procedures in VS Code: 3 rows affected and an OUTPUT parameter returning the new order Id" class="wp-image-3201" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-executesql-stored-procedure-output-parameter-rows-affected.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-executesql-stored-procedure-output-parameter-rows-affected-300x237.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-executesql-stored-procedure-output-parameter-rows-affected-1024x808.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-executesql-stored-procedure-output-parameter-rows-affected-768x606.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">ApplyDiscount reported 3 rows; AddOrder returned -1 but filled the OUTPUT parameter</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>ApplyDiscount: 3 rows affected
AddOrder: ExecuteSql returned -1, new order Id = 9</code></pre>



<p class="wp-block-paragraph"><code>ApplyDiscount</code> took 10% off the three Texas orders. <code>AddOrder</code> returned -1 because it starts with <code>SET NOCOUNT ON</code>, which stops SQL Server from reporting row counts.</p>



<p class="wp-block-paragraph">I checked the table afterward with sqlcmd:</p>



<pre class="wp-block-code"><code>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</code></pre>



<p class="wp-block-paragraph">Jenna&#8217;s $642.50 order is now $578.25, and Ava Sullivan&#8217;s Denver order got Id 9.</p>



<h3 class="wp-block-heading">OUTPUT Parameters with SqlParameter</h3>



<p class="wp-block-paragraph">An OUTPUT value needs a <code>SqlParameter</code> with <code>Direction = ParameterDirection.Output</code>, and the word <code>OUTPUT</code> after it in the SQL. Read <code>.Value</code> after the call finishes. Forget either part and the value stays <code>null</code>.</p>



<h2 class="wp-block-heading">EF Core LINQ vs Stored Procedures: Which Should You Use?</h2>



<p class="wp-block-paragraph">My verdict: write LINQ by default and call a stored procedure when the logic already lives in the database or LINQ can&#8217;t express it well.</p>



<figure class="wp-block-table"><table><thead><tr><th></th><th>EF Core LINQ</th><th>Stored procedure</th></tr></thead><tbody><tr><td>Type checking</td><td>Compile time</td><td>Column names checked at run time</td></tr><tr><td>Compose Where / OrderBy / paging</td><td>Yes, in SQL</td><td>No, only in memory</td></tr><tr><td>Change tracking</td><td>Yes</td><td>Yes with FromSql on a DbSet</td></tr><tr><td>Schema changes</td><td>Migrations update the model</td><td>You edit the procedure too</td></tr><tr><td>Good for</td><td>CRUD and most queries</td><td>Existing DBA-owned logic, heavy reports, bulk updates</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">For a typical <a href="https://aspdotnethelp.com/aspnet-core-web-api-crud-ef-core/">ASP.NET Core Web API with EF Core</a>, I keep CRUD in LINQ and use procedures for one or two reports. Both run as parameterized SQL, so I don&#8217;t pick a procedure for speed alone.</p>



<h2 class="wp-block-heading">Why Does Where() After a Stored Procedure Call Throw?</h2>



<p class="wp-block-paragraph">EF Core composes LINQ by wrapping your SQL in a subquery, and SQL Server can&#8217;t put an <code>EXEC</code> inside a <code>SELECT</code>. Same Texas orders, one filter added:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;

namespace W13Sproc;

public static class ComposeError
{
    public static async Task RunAsync()
    {
        using var db = new SalesDb();
        string state = &quot;TX&quot;;
        try
        {
            var big = await db.Orders.FromSql($&quot;EXEC dbo.GetOrdersByState {state}&quot;)
                .Where(o =&gt; o.Total &gt; 500m).ToListAsync();
        }
        catch (Exception ex) { Console.WriteLine($&quot;{ex.GetType().Name}: {ex.Message}&quot;); }

        // Fix: stop EF Core from composing; the filter runs in C#
        var bigOrders = await db.Orders.FromSql($&quot;EXEC dbo.GetOrdersByState {state}&quot;)
            .AsAsyncEnumerable().Where(o =&gt; o.Total &gt; 500m).ToListAsync();
        Console.WriteLine($&quot;AsAsyncEnumerable: {bigOrders.Count} TX orders over $500&quot;);
    }
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1092" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-stored-procedure-where-composable-error-asasyncenumerable.png" alt="EF Core InvalidOperationException for non-composable SQL when Where is added after FromSql EXEC, and the AsAsyncEnumerable fix returning 2 Texas orders over $500" class="wp-image-3205" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-stored-procedure-where-composable-error-asasyncenumerable.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-stored-procedure-where-composable-error-asasyncenumerable-300x237.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-stored-procedure-where-composable-error-asasyncenumerable-1024x808.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-stored-procedure-where-composable-error-asasyncenumerable-768x606.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">Where() after EXEC threw; AsAsyncEnumerable() moved the filter into C#</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>InvalidOperationException: &#x27;FromSql&#x27; or &#x27;SqlQuery&#x27; was called with non-composable SQL and with a query composing over it. Consider calling &#x27;AsEnumerable&#x27; after the method to perform the composition on the client side.
AsAsyncEnumerable: 2 TX orders over $500</code></pre>



<p class="wp-block-paragraph"><code>AsAsyncEnumerable()</code> (or <code>AsEnumerable()</code> in sync code) ends the SQL part of the query, so the <code>Where</code> runs as plain <a href="https://aspdotnethelp.com/linq-in-csharp/">LINQ in C#</a> over the returned rows. The <code>ToListAsync</code> after it is the <code>System.Linq.AsyncEnumerable</code> version built into .NET 10.</p>



<p class="wp-block-paragraph">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.</p>



<p class="wp-block-paragraph">Once your procedures work, these help wire them into a real app:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/dependency-injection-lifetimes-aspnet-core/">Dependency injection lifetimes for DbContext</a></li>

<li><a href="https://aspdotnethelp.com/cancellationtoken-in-csharp/">Pass a CancellationToken to long queries</a></li>

<li><a href="https://aspdotnethelp.com/appsettings-per-environment-aspnet-core/">Keep connection strings per environment</a></li>

<li><a href="https://aspdotnethelp.com/asp-net-core-tutorials/">All ASP.NET Core tutorials</a></li>
</ul>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-w13sp0000001" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I call a stored procedure in EF Core?</h3>
<div class="rank-math-answer ">

<p>Use <code>FromSql</code> on a <code>DbSet</code> when the procedure returns entity rows, for example <code>db.Orders.FromSql($"EXEC dbo.GetOrdersByState {state}")</code>. Use <code>Database.SqlQuery&lt;T&gt;</code> for other result shapes and <code>Database.ExecuteSql</code> for procedures that only change data.</p>

</div>
</div>
<div id="faq-question-w13sp0000002" class="rank-math-list-item">
<h3 class="rank-math-question ">Is FromSql safe from SQL injection?</h3>
<div class="rank-math-answer ">

<p>Yes. Every value in the interpolated string goes to SQL Server as a DbParameter. <code>FromSqlRaw</code> is only safe when you pass values as parameters, never concatenated into the SQL text.</p>

</div>
</div>
<div id="faq-question-w13sp0000003" class="rank-math-list-item">
<h3 class="rank-math-question ">Can I use Where or OrderBy after calling a stored procedure?</h3>
<div class="rank-math-answer ">

<p>Not in the database. SQL Server can&#8217;t compose over <code>EXEC</code>, so EF Core throws InvalidOperationException. Call <code>AsAsyncEnumerable()</code> or <code>AsEnumerable()</code> first, then filter in memory.</p>

</div>
</div>
<div id="faq-question-w13sp0000004" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I get an OUTPUT parameter from a stored procedure in EF Core?</h3>
<div class="rank-math-answer ">

<p>Create a <code>SqlParameter</code> with <code>Direction = ParameterDirection.Output</code>, pass it in the SQL followed by <code>OUTPUT</code>, and read its <code>Value</code> after <code>ExecuteSqlAsync</code> returns.</p>

</div>
</div>
<div id="faq-question-w13sp0000005" class="rank-math-list-item">
<h3 class="rank-math-question ">What is the difference between FromSql and SqlQuery in EF Core?</h3>
<div class="rank-math-answer ">

<p><code>FromSql</code> returns entities from your model and can track them. <code>SqlQuery&lt;T&gt;</code> maps rows to scalars or any unmapped type. Microsoft&#8217;s <a href="https://learn.microsoft.com/en-us/ef/core/querying/sql-queries" target="_blank" rel="noopener">SQL queries in EF Core</a> page covers both.</p>

</div>
</div>
</div>
</div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Download a File in Blazor (Stream, URL, Endpoint and CSV)</title>
		<link>https://aspdotnethelp.com/blazor-download-file/</link>
		
		<dc:creator><![CDATA[Bijay Kumar]]></dc:creator>
		<pubDate>Wed, 02 Dec 2026 15:15:00 +0000</pubDate>
				<category><![CDATA[Blazor]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=3096</guid>

					<description><![CDATA[If you need a Blazor download file button, wrap your .NET Stream in a DotNetStreamReference and pass it to a small JavaScript function that turns the bytes into a Blob and clicks a temporary link: Blazor has no built-in download API, so that&#8217;s where most people get stuck. I ran this pattern and three others ... <a title="How to Download a File in Blazor (Stream, URL, Endpoint and CSV)" class="read-more" href="https://aspdotnethelp.com/blazor-download-file/" aria-label="Read more about How to Download a File in Blazor (Stream, URL, Endpoint and CSV)">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">If you need a <strong>Blazor download file</strong> button, wrap your .NET <code>Stream</code> in a <code>DotNetStreamReference</code> and pass it to a small JavaScript function that turns the bytes into a Blob and clicks a temporary link:</p>



<pre class="wp-block-code"><code>using var streamRef = new DotNetStreamReference(stream: fileStream);
await JS.InvokeVoidAsync(&quot;downloadFileFromStream&quot;, &quot;invoice-1042.pdf&quot;, streamRef);</code></pre>



<p class="wp-block-paragraph">Blazor has no built-in download API, so that&#8217;s where most people get stuck. I ran this pattern and three others on .NET 10 and checked every file the browser really saved.</p>



<h2 class="wp-block-heading">The Sample Blazor App We&#8217;ll Use</h2>



<p class="wp-block-paragraph">The running sample is a downloads page for Bayside Outfitters, a made-up outdoor store in San Diego, California. It&#8217;s a Blazor Web App with the InteractiveServer render mode on .NET SDK 10.0.402 (<a href="https://aspdotnethelp.com/check-dotnet-version/">check your .NET version</a> first).</p>



<p class="wp-block-paragraph">New to Blazor? My <a href="https://aspdotnethelp.com/blazor-tutorial-for-beginners/">Blazor tutorial for beginners</a> walks through the template. Here&#8217;s what the page offers:</p>



<ul class="wp-block-list">
<li><code>invoice-1042.pdf</code> (625 bytes), kept in a private <code>Files</code> folder outside <code>wwwroot</code></li>

<li><code>return-policy-2026.txt</code> (223 bytes), a public file in <code>wwwroot/files</code></li>

<li><code>orders-2026-11.csv</code>, four US orders built in memory (177 bytes)</li>
</ul>



<p class="wp-block-paragraph">The private invoice is the tricky one: the browser can&#8217;t reach it by URL, so C# has to send the bytes.</p>



<pre class="wp-block-code"><code>dotnet new blazor -o W13BlazorDownload</code></pre>



<p class="wp-block-paragraph">I deleted <code>appsettings.Development.json</code>, trimmed <code>Program.cs</code> to plain http and set port 5911. Here are the four files as they ran:</p>



<pre class="wp-block-code"><code>{
  &quot;Logging&quot;: {
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Information&quot;,
      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;
    }
  },
  &quot;AllowedHosts&quot;: &quot;*&quot;
}</code></pre>



<pre class="wp-block-code"><code>{
  &quot;$schema&quot;: &quot;https://json.schemastore.org/launchsettings.json&quot;,
  &quot;profiles&quot;: {
    &quot;http&quot;: {
      &quot;commandName&quot;: &quot;Project&quot;,
      &quot;dotnetRunMessages&quot;: true,
      &quot;launchBrowser&quot;: false,
      &quot;applicationUrl&quot;: &quot;http://localhost:5911&quot;,
      &quot;environmentVariables&quot;: {
        &quot;ASPNETCORE_ENVIRONMENT&quot;: &quot;Development&quot;
      }
    }
  }
}</code></pre>



<pre class="wp-block-code"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;BlazorDisableThrowNavigationException&gt;true&lt;/BlazorDisableThrowNavigationException&gt;
  &lt;/PropertyGroup&gt;

&lt;/Project&gt;</code></pre>



<pre class="wp-block-code"><code>using W13BlazorDownload;
using W13BlazorDownload.Components;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

var app = builder.Build();
app.UseAntiforgery();
app.MapStaticAssets();
app.MapDownloadEndpoints();          // Method 3 + the CSV endpoint
app.MapRazorComponents&lt;App&gt;()
    .AddInteractiveServerRenderMode();
app.Run();</code></pre>



<p class="wp-block-paragraph">The page is <code>Components/Pages/Downloads.razor</code>. Every method below points back at one of its three buttons:</p>



<pre class="wp-block-code"><code>@page &quot;/downloads&quot;
@rendermode InteractiveServer
@inject IJSRuntime JS
@inject IWebHostEnvironment Env

&lt;PageTitle&gt;Downloads&lt;/PageTitle&gt;

&lt;h1&gt;Bayside Outfitters - Downloads&lt;/h1&gt;
&lt;p&gt;Order #1042 for Tyler Brooks, San Diego, CA&lt;/p&gt;

&lt;button id=&quot;invoice&quot; class=&quot;btn btn-primary&quot; @onclick=&quot;DownloadInvoice&quot;&gt;Invoice PDF (stream)&lt;/button&gt;
&lt;button id=&quot;policy&quot; class=&quot;btn btn-outline-primary&quot; @onclick=&quot;DownloadPolicy&quot;&gt;Return policy (URL)&lt;/button&gt;
&lt;button id=&quot;csv&quot; class=&quot;btn btn-success&quot; @onclick=&quot;ExportCsv&quot;&gt;Export orders CSV&lt;/button&gt;

&lt;ul class=&quot;mt-3&quot;&gt;
    @foreach (var line in log)
    {
        &lt;li&gt;@line&lt;/li&gt;
    }
&lt;/ul&gt;

@code {
    private readonly List&lt;string&gt; log = [];

    // Method 1: stream a file from the server&#x27;s private Files folder
    private async Task DownloadInvoice()
    {
        var path = Path.Combine(Env.ContentRootPath, &quot;Files&quot;, &quot;invoice-1042.pdf&quot;);
        var fileStream = File.OpenRead(path);
        var size = fileStream.Length;

        using var streamRef = new DotNetStreamReference(stream: fileStream);
        await JS.InvokeVoidAsync(&quot;downloadFileFromStream&quot;, &quot;invoice-1042.pdf&quot;, streamRef);
        log.Add($&quot;Streamed invoice-1042.pdf ({size} bytes)&quot;);
    }

    // Method 2: let the browser fetch a public file by URL
    private async Task DownloadPolicy()
    {
        await JS.InvokeVoidAsync(&quot;triggerFileDownload&quot;,
            &quot;return-policy-2026.txt&quot;, &quot;/files/return-policy-2026.txt&quot;);
        log.Add(&quot;Sent the browser to /files/return-policy-2026.txt&quot;);
    }

    // Method 4: build a CSV in memory and stream it
    private async Task ExportCsv()
    {
        byte[] csv = OrderCsv.Build();
        using var streamRef = new DotNetStreamReference(new MemoryStream(csv));
        await JS.InvokeVoidAsync(&quot;downloadFileFromStream&quot;, &quot;orders-2026-11.csv&quot;, streamRef);
        log.Add($&quot;Exported {OrderCsv.Orders.Length} orders ({csv.Length} bytes)&quot;);
    }
}</code></pre>



<p class="wp-block-paragraph">I clicked all three buttons in headless Edge with its download folder set to <code>BrowserDownloads\interactive</code>:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1002" height="331" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-download-file-buttons-page.png" alt="Blazor download file demo page in Edge with Invoice PDF, Return policy and Export orders CSV buttons and a log showing 625 bytes streamed and 4 orders exported" class="wp-image-3193" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-download-file-buttons-page.png 1002w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-download-file-buttons-page-300x99.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-download-file-buttons-page-768x254.png 768w" sizes="auto, (max-width: 1002px) 100vw, 1002px" /><figcaption class="wp-element-caption">The Bayside Outfitters downloads page after all three buttons were clicked</figcaption></figure>
</div>


<h2 class="wp-block-heading">Method 1: Stream a File to the Browser With DotNetStreamReference (Recommended)</h2>



<p class="wp-block-paragraph">Use this when your file is under about 250 MB and your users can&#8217;t fetch it by URL, like a private invoice. Same Bayside app: the first button streams <code>invoice-1042.pdf</code> from the server&#8217;s <code>Files</code> folder.</p>



<p class="wp-block-paragraph">First, the JavaScript. I put Microsoft&#8217;s two helper functions in <code>wwwroot/js/file-download.js</code>:</p>



<pre class="wp-block-code"><code>window.downloadFileFromStream = async (fileName, contentStreamReference) =&gt; {
  const arrayBuffer = await contentStreamReference.arrayBuffer();
  const blob = new Blob([arrayBuffer]);
  const url = URL.createObjectURL(blob);
  const anchorElement = document.createElement(&#x27;a&#x27;);
  anchorElement.href = url;
  anchorElement.download = fileName ?? &#x27;&#x27;;
  anchorElement.click();
  anchorElement.remove();
  URL.revokeObjectURL(url);
}

window.triggerFileDownload = (fileName, url) =&gt; {
  const anchorElement = document.createElement(&#x27;a&#x27;);
  anchorElement.href = url;
  anchorElement.download = fileName ?? &#x27;&#x27;;
  anchorElement.click();
  anchorElement.remove();
}</code></pre>



<p class="wp-block-paragraph">Then <code>App.razor</code> loads that file right after the Blazor script:</p>



<pre class="wp-block-code"><code>&lt;body&gt;
    &lt;Routes /&gt;
    &lt;ReconnectModal /&gt;
    &lt;script src=&quot;@Assets[&quot;_framework/blazor.web.js&quot;]&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;@Assets[&quot;js/file-download.js&quot;]&quot;&gt;&lt;/script&gt;
&lt;/body&gt;</code></pre>



<p class="wp-block-paragraph">The C# side is <code>DownloadInvoice</code> in the page above. Edge reported a download from a blob URL, and the saved file matched the original byte for byte:</p>



<pre class="wp-block-code"><code>[download] begin invoice-1042.pdf from blob: object URL
[download] completed invoice-1042.pdf 625 bytes</code></pre>



<pre class="wp-block-code"><code>Comparing files FILES\invoice-1042.pdf and BROWSERDOWNLOADS\INTERACTIVE\INVOICE-1042.PDF
FC: no differences encountered

invoice-1042.pdf  625 bytes
orders-2026-11.csv  177 bytes
return-policy-2026.txt  223 bytes</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1592" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-download-file-from-stream-fc-check.png" alt="VS Code with file-download.js open and the terminal showing fc reporting no differences between the server invoice and the downloaded invoice-1042.pdf, plus the three downloaded files with their sizes" class="wp-image-3196" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-download-file-from-stream-fc-check.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-download-file-from-stream-fc-check-261x300.png 261w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-download-file-from-stream-fc-check-890x1024.png 890w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-download-file-from-stream-fc-check-768x883.png 768w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-download-file-from-stream-fc-check-1335x1536.png 1335w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">file-download.js next to the fc check of the downloaded invoice</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>How does this code work?</strong></p>



<p class="wp-block-paragraph"><code>DotNetStreamReference</code> tells Blazor to send the bytes over its native byte-streaming interop instead of serializing them to JSON. On the JS side, <code>arrayBuffer()</code> reads the whole stream into browser memory.</p>



<p class="wp-block-paragraph">The function wraps that buffer in a <code>Blob</code>, makes an object URL, and clicks an anchor whose <code>download</code> attribute carries the file name. The <code>await</code> matters (<a href="https://aspdotnethelp.com/async-await-in-csharp/">async and await in C#</a> explains why): the call returns once the browser has the bytes.</p>



<p class="wp-block-paragraph">The constructor is <code>DotNetStreamReference(Stream stream, bool leaveOpen = false)</code>, so you don&#8217;t close the file stream yourself; Blazor does it after the transfer. That&#8217;s why I read <code>fileStream.Length</code> before the call, not after.</p>



<p class="wp-block-paragraph"><strong>Important:</strong> keep <code>URL.revokeObjectURL(url)</code>. Microsoft calls it the step that stops memory leaking on the client, the browser-side cousin of the <a href="https://aspdotnethelp.com/dispose-and-finalize-in-csharp/">Dispose pattern in C#</a>.</p>



<h2 class="wp-block-heading">Method 2: Download a File From a URL With triggerFileDownload</h2>



<p class="wp-block-paragraph">Use this when your file already sits at a URL your users can reach, and for anything 250 MB or bigger. Nothing streams through the circuit; the browser fetches the file itself.</p>



<p class="wp-block-paragraph">Same Bayside app, second button. The public file is <code>wwwroot/files/return-policy-2026.txt</code>:</p>



<pre class="wp-block-code"><code>Bayside Outfitters - Return Policy (2026)
Unworn items can be returned within 30 days with the receipt.
Refunds go back to the original card in 5-7 business days.
Questions? Call (619) 555-0148, Mon-Fri 9 AM - 5 PM PT.</code></pre>



<p class="wp-block-paragraph"><code>DownloadPolicy</code> hands the name and the relative URL to <code>triggerFileDownload</code> from Method 1&#8217;s JS file. Edge saved all 223 bytes straight from the server:</p>



<pre class="wp-block-code"><code>[download] begin return-policy-2026.txt from http://localhost:5911/files/return-policy-2026.txt
[download] completed return-policy-2026.txt 223 bytes</code></pre>



<p class="wp-block-paragraph"><strong>How does this code work?</strong></p>



<p class="wp-block-paragraph">It&#8217;s the same anchor trick without the Blob. Static files don&#8217;t send a <code>Content-Disposition</code> header, so the <code>download</code> attribute is what turns this request into a save:</p>



<pre class="wp-block-code"><code>HTTP/1.1 200 OK
Content-Length: 223
Content-Type: text/plain
Accept-Ranges: bytes</code></pre>



<p class="wp-block-paragraph">So here&#8217;s the catch: browsers only honor <code>download</code> for same-origin URLs. I called the same function with <code>http://127.0.0.1:5911/...</code>, a different origin than <code>localhost:5911</code>.</p>



<p class="wp-block-paragraph">Nothing was saved. Edge simply opened the text file, and the tab ended up on <code>http://127.0.0.1:5911/files/return-policy-2026.txt</code> showing the policy text. For files on a CDN or another API, set up <a href="https://aspdotnethelp.com/cors-in-aspnet-core/">CORS in ASP.NET Core</a> or serve a Content-Disposition header.</p>



<h2 class="wp-block-heading">Method 3: Download a File From a Minimal API Endpoint With Results.File</h2>



<p class="wp-block-paragraph">Use this when you serve big files, files behind a permission check, or pages that aren&#8217;t interactive. A plain link works in every render mode because no JavaScript or circuit is involved.</p>



<p class="wp-block-paragraph">Same Bayside app, same invoice. I put two endpoints in <code>DownloadEndpoints.cs</code> and mapped them with one line in <code>Program.cs</code>:</p>



<pre class="wp-block-code"><code>namespace W13BlazorDownload;

public static class DownloadEndpoints
{
    public static void MapDownloadEndpoints(this WebApplication app)
    {
        var folder = Path.Combine(app.Environment.ContentRootPath, &quot;Files&quot;);

        app.MapGet(&quot;/files/invoice/{id:int}&quot;, (int id) =&gt;
        {
            var path = Path.Combine(folder, $&quot;invoice-{id}.pdf&quot;);
            return File.Exists(path)
                ? Results.File(path, &quot;application/pdf&quot;, $&quot;invoice-{id}.pdf&quot;)
                : Results.NotFound();
        });

        app.MapGet(&quot;/reports/orders.csv&quot;, () =&gt;
            Results.File(OrderCsv.Build(), &quot;text/csv&quot;, &quot;orders-2026-11.csv&quot;));
    }
}</code></pre>



<p class="wp-block-paragraph">The static SSR page <code>Components/Pages/Reports.razor</code> has no <code>@rendermode</code>, just two links:</p>



<pre class="wp-block-code"><code>@page &quot;/reports&quot;

&lt;PageTitle&gt;Reports&lt;/PageTitle&gt;

&lt;h1&gt;Bayside Outfitters - Reports&lt;/h1&gt;
&lt;p&gt;Static SSR page: no circuit, no JavaScript interop, just links.&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;&lt;a id=&quot;orders-link&quot; href=&quot;/reports/orders.csv&quot; download&gt;November 2026 orders (CSV)&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a id=&quot;invoice-link&quot; href=&quot;/files/invoice/1042&quot; download&gt;Invoice #1042 (PDF)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1002" height="251" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-download-file-static-ssr-links.png" alt="Static SSR Blazor Reports page with two download links: November 2026 orders CSV and Invoice 1042 PDF" class="wp-image-3195" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-download-file-static-ssr-links.png 1002w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-download-file-static-ssr-links-300x75.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-download-file-static-ssr-links-768x192.png 768w" sizes="auto, (max-width: 1002px) 100vw, 1002px" /><figcaption class="wp-element-caption">The static SSR Reports page: plain links, no circuit</figcaption></figure>
</div>


<p class="wp-block-paragraph">Clicking both links in Edge saved <code>orders-2026-11.csv</code> and <code>invoice-1042.pdf</code>. curl shows the header that makes it work, and the 404 for an invoice that doesn&#8217;t exist:</p>



<pre class="wp-block-code"><code>HTTP/1.1 200 OK
Content-Length: 625
Content-Type: application/pdf
Date: Sun, 08 Nov 2026 02:49:42 GMT
Server: Kestrel
Last-Modified: Sun, 08 Nov 2026 02:49:33 GMT
Content-Disposition: attachment; filename=invoice-1042.pdf; filename*=UTF-8&#x27;&#x27;invoice-1042.pdf

invoice 9999: 404</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1592" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-results-file-content-disposition-header.png" alt="VS Code with DownloadEndpoints.cs open and the terminal showing curl output with Content-Type application/pdf, Content-Disposition attachment filename invoice-1042.pdf and a 404 for invoice 9999" class="wp-image-3198" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-results-file-content-disposition-header.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-results-file-content-disposition-header-261x300.png 261w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-results-file-content-disposition-header-890x1024.png 890w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-results-file-content-disposition-header-768x883.png 768w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-results-file-content-disposition-header-1335x1536.png 1335w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">Results.File sends Content-Disposition: attachment with the file name</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>How does this code work?</strong></p>



<p class="wp-block-paragraph"><code>Results.File</code> takes the path, the content type and <code>fileDownloadName</code>. The name becomes <code>Content-Disposition: attachment</code>, which tells any browser to save the response instead of showing it.</p>



<p class="wp-block-paragraph">The <code>{id:int}</code> constraint and the fixed <code>invoice-{id}.pdf</code> pattern mean nobody can ask for <code>../appsettings.json</code>. Kestrel streams the file from disk, so a 2 GB file never sits in memory.</p>



<p class="wp-block-paragraph">What happens without <code>download</code> on the link? I added one to the Reports page. Blazor&#8217;s enhanced navigation grabbed the click first and logged:</p>



<pre class="wp-block-code"><code>Enhanced navigation failed for destination http://localhost:5911/reports/orders.csv. Falling back to full page load.</code></pre>



<p class="wp-block-paragraph">The full page load still saved the CSV, thanks to the header. Keep <code>download</code> on file links anyway: it skips that wasted fetch. This is the <a href="https://aspdotnethelp.com/minimal-api-vs-controllers-aspnet-core/">minimal API</a> style; a controller&#8217;s <code>File()</code> works the same way.</p>



<p class="wp-block-paragraph"><strong>Pro Tip:</strong> pass <code>enableRangeProcessing: true</code> for large files so browsers can resume a broken download. Watch the overloads: for <code>byte[]</code> it&#8217;s the 4th parameter, for a path or <code>Stream</code> it&#8217;s the last.</p>



<h2 class="wp-block-heading">Method 4: Generate a CSV File on the Fly and Download It in Blazor</h2>



<p class="wp-block-paragraph">Use this when you need an export: a report, a filtered grid, an order history. Your file never touches disk. Same Bayside orders: four sales from California, Texas, Colorado and Oregon.</p>



<p class="wp-block-paragraph">Here&#8217;s <code>OrderCsv.cs</code>, built with a <a href="https://aspdotnethelp.com/difference-between-string-and-stringbuilder-in-csharp/">StringBuilder</a> and a <a href="https://aspdotnethelp.com/csharp-record-vs-class-vs-struct/">record</a> for each order:</p>



<pre class="wp-block-code"><code>using System.Globalization;
using System.Text;

namespace W13BlazorDownload;

public record Order(int Id, string Customer, string City, string State, decimal Total);

public static class OrderCsv
{
    public static readonly Order[] Orders =
    [
        new(1042, &quot;Tyler Brooks&quot;, &quot;San Diego&quot;, &quot;CA&quot;, 184.50m),
        new(1043, &quot;Jenna Morales&quot;, &quot;Austin&quot;, &quot;TX&quot;, 92.00m),
        new(1044, &quot;Marcus Reed&quot;, &quot;Denver&quot;, &quot;CO&quot;, 1249.99m),
        new(1045, &quot;Olivia Chen&quot;, &quot;Portland&quot;, &quot;OR&quot;, 37.25m),
    ];

    public static byte[] Build()
    {
        var sb = new StringBuilder(&quot;OrderId,Customer,City,State,Total\n&quot;);
        foreach (var o in Orders)
            sb.Append(CultureInfo.InvariantCulture,
                $&quot;{o.Id},{o.Customer},{o.City},{o.State},{o.Total:F2}\n&quot;);
        return Encoding.UTF8.GetBytes(sb.ToString());
    }
}</code></pre>



<p class="wp-block-paragraph">The third button calls <code>ExportCsv</code>: <code>OrderCsv.Build()</code>, a <code>MemoryStream</code>, and the same <code>downloadFileFromStream</code> function as Method 1. Edge saved 177 bytes, and the file opened like this:</p>



<pre class="wp-block-code"><code>OrderId,Customer,City,State,Total
1042,Tyler Brooks,San Diego,CA,184.50
1043,Jenna Morales,Austin,TX,92.00
1044,Marcus Reed,Denver,CO,1249.99
1045,Olivia Chen,Portland,OR,37.25</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1592" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-export-csv-downloaded-file.png" alt="VS Code with OrderCsv.cs open and the terminal printing the downloaded orders-2026-11.csv: a header row and four US orders from San Diego, Austin, Denver and Portland" class="wp-image-3197" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-export-csv-downloaded-file.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-export-csv-downloaded-file-261x300.png 261w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-export-csv-downloaded-file-890x1024.png 890w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-export-csv-downloaded-file-768x883.png 768w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-export-csv-downloaded-file-1335x1536.png 1335w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">OrderCsv.cs next to the CSV file the browser saved</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>How does this code work?</strong></p>



<p class="wp-block-paragraph"><code>CultureInfo.InvariantCulture</code> keeps the decimal point a period on every server, so 1249.99 doesn&#8217;t come out as 1249,99 on a German machine. <code>F2</code> gives every total two decimals.</p>



<p class="wp-block-paragraph"><code>Encoding.UTF8.GetBytes</code> turns the text into the bytes the stream carries. The <code>/reports/orders.csv</code> endpoint from Method 3 returns the exact same 177 bytes, so a static page can export too.</p>



<p class="wp-block-paragraph"><strong>Important:</strong> this sample has no commas or quotes inside values. Your real data will, so wrap those fields in double quotes (and double any quote inside) or use a CSV library.</p>



<h2 class="wp-block-heading">Does Blazor File Download Work in Every Render Mode?</h2>



<p class="wp-block-paragraph">Not every method. Methods 1, 2 and 4 call JavaScript from a button&#8217;s <code>@onclick</code>, so your component needs an interactive render mode. My <a href="https://aspdotnethelp.com/blazor-render-modes/">Blazor render modes guide</a> explains the options.</p>



<figure class="wp-block-table"><table><thead><tr><th>Render mode</th><th>Stream (1, 4)</th><th>URL via JS (2)</th><th>Endpoint link (3)</th></tr></thead><tbody><tr><td>Static SSR</td><td>No</td><td>Only with your own addEventListener</td><td>Yes</td></tr><tr><td>InteractiveServer</td><td>Yes</td><td>Yes</td><td>Yes</td></tr><tr><td>InteractiveWebAssembly</td><td>Yes</td><td>Yes</td><td>Yes</td></tr><tr><td>InteractiveAuto</td><td>Yes</td><td>Yes</td><td>Yes</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">On Blazor Server the bytes travel over the SignalR circuit, so a huge stream ties it up. Going the other way? See my guide to <a href="https://aspdotnethelp.com/upload-files-aspnet-core-web-api/">uploading files to an ASP.NET Core Web API</a>.</p>



<h2 class="wp-block-heading">Which Blazor Download File Method Should You Use?</h2>



<figure class="wp-block-table"><table><thead><tr><th>Situation</th><th>Use</th></tr></thead><tbody><tr><td>Private file under ~250 MB, interactive page</td><td>Method 1: <code>DotNetStreamReference</code></td></tr><tr><td>Public file in wwwroot, same origin</td><td>Method 2: <code>triggerFileDownload</code></td></tr><tr><td>Large file, auth check, or static SSR page</td><td>Method 3: <code>Results.File</code> + <code>&lt;a download&gt;</code></td></tr><tr><td>Export generated in C#</td><td>Method 4: <code>MemoryStream</code> + Method 1</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">If you&#8217;re unsure, build the endpoint first; it works everywhere. Files in <a href="https://aspdotnethelp.com/azure-blob-storage-csharp/">Azure Blob Storage</a> fit that path too: stream the blob from the endpoint.</p>



<h2 class="wp-block-heading">Things to Keep in Mind</h2>



<ul class="wp-block-list">
<li>The stream approach loads the whole file into browser memory. Past ~250 MB, switch to a URL or an endpoint.</li>

<li>Always call <code>URL.revokeObjectURL</code> after the click, or every download leaks a Blob.</li>

<li>The <code>download</code> attribute is ignored for cross-origin URLs; send <code>Content-Disposition: attachment</code> from the server instead.</li>

<li>Never build a file path from raw user input. Map an ID to a known folder, like the <code>{id:int}</code> route here.</li>

<li>JS interop doesn&#8217;t run on static SSR pages. Use an endpoint link there.</li>
</ul>



<p class="wp-block-paragraph">Once downloads work, these Bayside follow-ups pair well with them:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/blazor-tutorials/">All Blazor tutorials on the site</a></li>

<li><a href="https://aspdotnethelp.com/blazor-javascript-interop/">Blazor JavaScript interop, both directions</a></li>

<li><a href="https://aspdotnethelp.com/blazor-quickgrid/">Show the orders in a Blazor QuickGrid first</a></li>

<li><a href="https://aspdotnethelp.com/blazor-components/">Turn the download button into a reusable component</a></li>
</ul>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-w13dl0000001" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I download a file in Blazor?</h3>
<div class="rank-math-answer ">

<p>Wrap a Stream in DotNetStreamReference and call a JavaScript function such as downloadFileFromStream with JS.InvokeVoidAsync. The function reads the stream into an ArrayBuffer, creates a Blob and an object URL, and clicks an anchor with the download attribute.</p>

</div>
</div>
<div id="faq-question-w13dl0000002" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I download a file from a URL in Blazor?</h3>
<div class="rank-math-answer ">

<p>Create an anchor element in JavaScript, set href to the URL and download to the file name, then call click(). This works for same-origin URLs; for another origin the browser ignores the download attribute, so configure CORS or send Content-Disposition.</p>

</div>
</div>
<div id="faq-question-w13dl0000003" class="rank-math-list-item">
<h3 class="rank-math-question ">What is the file size limit for Blazor file downloads?</h3>
<div class="rank-math-answer ">

<p>There&#8217;s no hard limit, but Microsoft recommends the stream approach for files under 250 MB because the whole file lands in browser memory. For 250 MB or more, download from a URL or a server endpoint.</p>

</div>
</div>
<div id="faq-question-w13dl0000004" class="rank-math-list-item">
<h3 class="rank-math-question ">Can I download a file in Blazor without JavaScript?</h3>
<div class="rank-math-answer ">

<p>Yes. Map an endpoint that returns Results.File(path, contentType, fileDownloadName) and link to it with an a tag that has the download attribute. It works on static SSR pages too.</p>

</div>
</div>
<div id="faq-question-w13dl0000005" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I set the downloaded file name in Blazor?</h3>
<div class="rank-math-answer ">

<p>With JS interop, the anchor&#8217;s download attribute sets it. From an endpoint, pass fileDownloadName to Results.File, which sends Content-Disposition: attachment. Microsoft Learn&#8217;s <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/file-downloads?view=aspnetcore-10.0" target="_blank" rel="noopener">ASP.NET Core Blazor file downloads</a> page covers both.</p>

</div>
</div>
</div>
</div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Generics in C# with Examples (Classes, Methods, Constraints)</title>
		<link>https://aspdotnethelp.com/generics-in-csharp/</link>
		
		<dc:creator><![CDATA[Bijay Kumar]]></dc:creator>
		<pubDate>Tue, 01 Dec 2026 21:20:00 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=3095</guid>

					<description><![CDATA[Say you&#8217;re building the back office for a Phoenix landscaping company. You need in-memory stores for customers, work orders and invoices, and all three classes would be the same 30 lines with a new type name. C# generics fix that: you write Repository&#60;T&#62; once, and the compiler checks every type you plug in. We&#8217;ll build ... <a title="Generics in C# with Examples (Classes, Methods, Constraints)" class="read-more" href="https://aspdotnethelp.com/generics-in-csharp/" aria-label="Read more about Generics in C# with Examples (Classes, Methods, Constraints)">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Say you&#8217;re building the back office for a Phoenix landscaping company. You need in-memory stores for customers, work orders and invoices, and all three classes would be the same 30 lines with a new type name.</p>



<p class="wp-block-paragraph"><strong>C# generics</strong> fix that: you write <code>Repository&lt;T&gt;</code> once, and the compiler checks every type you plug in. We&#8217;ll build that store on .NET 10, then add constraints.</p>



<p class="wp-block-paragraph"><strong>Quick answer:</strong> put a type parameter in angle brackets (<code>class Repository&lt;T&gt;</code>, <code>T Largest&lt;T&gt;(T[] items)</code>) and limit it with <code>where T : ...</code>.</p>



<h2 class="wp-block-heading">Why Use Generics in C# Instead of object?</h2>



<p class="wp-block-paragraph">Before generics, a shared store kept everything as <code>object</code>, like the old <a href="https://aspdotnethelp.com/arraylist-in-csharp/">ArrayList</a>. That has two costs: wrong types only fail at run time, and every value type gets boxed. This program shows both:</p>



<pre class="wp-block-code"><code>#:property PublishAot=false
using System.Collections;
using System.Globalization;
CultureInfo.CurrentCulture = new(&quot;en-US&quot;);

var totals = new ArrayList { 1250, 980, 4310 };   // order totals
totals.Add(&quot;1,100&quot;);                              // compiles fine
try { foreach (object o in totals) _ = (int)o; }
catch (InvalidCastException) { Console.WriteLine(&quot;ArrayList: InvalidCastException at run time&quot;); }

long t0 = GC.GetAllocatedBytesForCurrentThread();
var boxed = new ArrayList();
for (int i = 0; i &lt; 100_000; i++) boxed.Add(i);   // boxes every int
long t1 = GC.GetAllocatedBytesForCurrentThread();
var typed = new List&lt;int&gt;();
for (int i = 0; i &lt; 100_000; i++) typed.Add(i);   // no boxing
long t2 = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($&quot;ArrayList: {t1 - t0:N0} bytes allocated&quot;);
Console.WriteLine($&quot;List&lt;int&gt;: {t2 - t1:N0} bytes allocated&quot;);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>ArrayList: InvalidCastException at run time
ArrayList: 4,497,536 bytes allocated
List&lt;int&gt;: 1,048,976 bytes allocated</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1284" height="1142" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generics-vs-object-arraylist-boxing-allocations-vscode.png" alt="C# generics vs object: ArrayList throws InvalidCastException at run time and allocates far more bytes than List&lt;int&gt; for 100,000 integers in VS Code" class="wp-image-3190" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generics-vs-object-arraylist-boxing-allocations-vscode.png 1284w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generics-vs-object-arraylist-boxing-allocations-vscode-300x267.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generics-vs-object-arraylist-boxing-allocations-vscode-1024x911.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generics-vs-object-arraylist-boxing-allocations-vscode-768x683.png 768w" sizes="auto, (max-width: 1284px) 100vw, 1284px" /><figcaption class="wp-element-caption">The ArrayList fails only when it runs, and boxing costs real memory</figcaption></figure>
</div>


<p class="wp-block-paragraph">Adding the string <code>"1,100"</code> compiled fine and blew up later. For 100,000 numbers, <code>ArrayList</code> allocated 4,497,536 bytes against 1,048,976 for <code>List&lt;int&gt;</code>, because each boxed int is its own heap object. My <a href="https://aspdotnethelp.com/boxing-and-unboxing-in-csharp/">boxing and unboxing guide</a> digs into why.</p>



<p class="wp-block-paragraph">With a generic list, the bad line doesn&#8217;t compile at all, and the numbers stay inline in one array.</p>



<h2 class="wp-block-heading">Generic Classes Example: Repository&lt;T&gt; and Result&lt;T&gt;</h2>



<p class="wp-block-paragraph">A generic class names its type parameter after the class name. Here&#8217;s the landscaping store: one <code>Repository&lt;T&gt;</code> serving customers, orders and invoices, all <a href="https://aspdotnethelp.com/csharp-record-vs-class-vs-struct/">records</a>:</p>



<pre class="wp-block-code"><code>#:property PublishAot=false

var customers = new Repository&lt;Customer&gt;();
customers.Add(new Customer(1, &quot;Jenna Morales&quot;, &quot;Phoenix, AZ&quot;));
customers.Add(new Customer(2, &quot;Tyler Brooks&quot;, &quot;Austin, TX&quot;));
var orders = new Repository&lt;Order&gt;();
orders.Add(new Order(501, 2, &quot;TX&quot;));
var invoices = new Repository&lt;Invoice&gt;();
invoices.Add(new Invoice(1001, 2, 1249.50m));

Console.WriteLine(customers.GetById(2));
Console.WriteLine(orders.GetById(501));
Console.WriteLine(invoices.GetById(1001));
Console.WriteLine($&quot;Customers: {customers.Count}, missing: {customers.GetById(9)}&quot;);

interface IEntity { int Id { get; } }
record Customer(int Id, string Name, string City) : IEntity;
record Order(int Id, int CustomerId, string State) : IEntity;
record Invoice(int Id, int CustomerId, decimal Amount) : IEntity;

class Repository&lt;T&gt; where T : IEntity
{
    private readonly Dictionary&lt;int, T&gt; _items = [];
    public void Add(T item) =&gt; _items[item.Id] = item;
    public T? GetById(int id) =&gt; _items.GetValueOrDefault(id);
    public int Count =&gt; _items.Count;
}</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>Customer { Id = 2, Name = Tyler Brooks, City = Austin, TX }
Order { Id = 501, CustomerId = 2, State = TX }
Invoice { Id = 1001, CustomerId = 2, Amount = 1249.50 }
Customers: 2, missing:</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1284" height="1142" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-class-repository-t-customer-order-invoice.png" alt="C# generic class Repository&lt;T&gt; where T : IEntity storing Customer, Order and Invoice records, with GetById output in the VS Code terminal" class="wp-image-3185" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-class-repository-t-customer-order-invoice.png 1284w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-class-repository-t-customer-order-invoice-300x267.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-class-repository-t-customer-order-invoice-1024x911.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-class-repository-t-customer-order-invoice-768x683.png 768w" sizes="auto, (max-width: 1284px) 100vw, 1284px" /><figcaption class="wp-element-caption">One generic class, three closed types: Repository<Customer>, Repository<Order>, Repository<Invoice></figcaption></figure>
</div>


<p class="wp-block-paragraph">Each <code>new Repository&lt;Customer&gt;()</code> is a separate closed type, and <code>Add</code> on it only accepts a <code>Customer</code>. The <code>where T : IEntity</code> line is what lets the class read <code>item.Id</code>; I explain it in the constraints section.</p>



<p class="wp-block-paragraph">Asking for ID 9 printed nothing, because <code>GetValueOrDefault</code> returned <code>null</code> for a missing record. Inside it is a <a href="https://aspdotnethelp.com/dictionary-in-csharp/">Dictionary<int, T></a>, itself a generic class.</p>



<h3 class="wp-block-heading">A Generic Result&lt;T&gt; Wrapper</h3>



<p class="wp-block-paragraph">The other generic class I add to almost every project is a small result type, so a method can return a value or a reason it failed:</p>



<pre class="wp-block-code"><code>#:property PublishAot=false

Result&lt;decimal&gt; quote = Result&lt;decimal&gt;.Ok(89.99m);
Result&lt;decimal&gt; denied = Result&lt;decimal&gt;.Fail(&quot;We don&#x27;t ship to ZIP 99501 yet&quot;);

Console.WriteLine(quote);
Console.WriteLine(denied);

record Result&lt;T&gt;(bool Success, T? Value, string? Error)
{
    public static Result&lt;T&gt; Ok(T value) =&gt; new(true, value, null);
    public static Result&lt;T&gt; Fail(string error) =&gt; new(false, default, error);
}</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>Result { Success = True, Value = 89.99, Error =  }
Result { Success = False, Value = 0, Error = We don&#x27;t ship to ZIP 99501 yet }</code></pre>



<p class="wp-block-paragraph"><code>Result&lt;decimal&gt;</code> holds a price here, and the same record could hold an <code>Invoice</code> tomorrow. <code>default</code> fills <code>Value</code> on failure, which is <code>0</code> for a decimal.</p>



<h2 class="wp-block-heading">Generic Methods Example with Type Inference</h2>



<p class="wp-block-paragraph">A method can have its own type parameter even inside a normal class. Usually you don&#8217;t write the type at the call: the compiler infers it from the arguments.</p>



<pre class="wp-block-code"><code>#:property PublishAot=false

int[] zips = [85004, 78701, 10001];
string[] names = [&quot;Tyler&quot;, &quot;Jenna&quot;, &quot;Marcus&quot;];

Console.WriteLine(Largest(zips));        // T inferred as int
Console.WriteLine(Largest(names));       // T inferred as string
Console.WriteLine(Largest&lt;decimal&gt;([19.99m, 249.50m, 5m]));

var (from, to) = (&quot;Phoenix&quot;, &quot;Denver&quot;);
Swap(ref from, ref to);
Console.WriteLine($&quot;{from} -&gt; {to}&quot;);

static T Largest&lt;T&gt;(T[] items) where T : IComparable&lt;T&gt;
{
    T best = items[0];
    foreach (T item in items)
        if (item.CompareTo(best) &gt; 0) best = item;
    return best;
}
static void Swap&lt;T&gt;(ref T x, ref T y) =&gt; (x, y) = (y, x);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>85004
Tyler
249.50
Denver -&gt; Phoenix</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1284" height="1142" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-method-type-inference-icomparable-largest.png" alt="C# generic method Largest&lt;T&gt; where T : IComparable&lt;T&gt; called with int ZIP codes, strings and decimals, plus a generic Swap&lt;T&gt; with ref parameters" class="wp-image-3188" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-method-type-inference-icomparable-largest.png 1284w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-method-type-inference-icomparable-largest-300x267.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-method-type-inference-icomparable-largest-1024x911.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-method-type-inference-icomparable-largest-768x683.png 768w" sizes="auto, (max-width: 1284px) 100vw, 1284px" /><figcaption class="wp-element-caption">The compiler infers T from the argument; Largest<decimal> passes it explicitly</figcaption></figure>
</div>


<p class="wp-block-paragraph"><code>Largest(zips)</code> became <code>Largest&lt;int&gt;</code> on its own. I passed <code>&lt;decimal&gt;</code> on the third call, which is the long form you need when the arguments don&#8217;t pin the type down.</p>



<p class="wp-block-paragraph"><a href="https://aspdotnethelp.com/linq-in-csharp/">LINQ</a> is built from generic methods just like this one, which is why <code>Where</code> and <code>Select</code> work on any sequence.</p>



<h2 class="wp-block-heading">Generics with Multiple Type Parameters (TKey, TValue)</h2>



<p class="wp-block-paragraph">Separate the parameters with commas and give each a name that says what it is. Microsoft&#8217;s convention is a <code>T</code> prefix: <code>TKey</code>, <code>TValue</code>, <code>TIn</code>, <code>TOut</code>.</p>



<pre class="wp-block-code"><code>#:property PublishAot=false

var taxRates = new Lookup&lt;string, decimal&gt;();
taxRates.Set(&quot;AZ&quot;, 0.056m);
taxRates.Set(&quot;TX&quot;, 0.0625m);
Console.WriteLine($&quot;TX rate: {taxRates.Get(&quot;TX&quot;)}&quot;);
Console.WriteLine(Map&lt;int, string&gt;(85004, zip =&gt; $&quot;ZIP {zip}&quot;));
Console.WriteLine(Map(3, n =&gt; n * 19.99m));   // TIn int, TOut decimal

static TOut Map&lt;TIn, TOut&gt;(TIn input, Func&lt;TIn, TOut&gt; convert) =&gt; convert(input);

class Lookup&lt;TKey, TValue&gt; where TKey : notnull
{
    private readonly Dictionary&lt;TKey, TValue&gt; _map = [];
    public void Set(TKey key, TValue value) =&gt; _map[key] = value;
    public TValue Get(TKey key) =&gt; _map[key];
}</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>TX rate: 0.0625
ZIP 85004
59.97</code></pre>



<p class="wp-block-paragraph">Each parameter can have its own constraint, so <code>TKey</code> is <code>notnull</code> while <code>TValue</code> stays open. <code>Func&lt;TIn, TOut&gt;</code> is a generic delegate; my <a href="https://aspdotnethelp.com/delegates-in-csharp/">C# delegates tutorial</a> covers <code>Func</code> and <code>Action</code>.</p>



<h2 class="wp-block-heading">C# Generics Constraints: Every where Clause</h2>



<p class="wp-block-paragraph">Without a constraint, the compiler only lets you use what every type has: the members of <code>object</code>. A constraint promises more, and the compiler rejects type arguments that break the promise.</p>



<figure class="wp-block-table"><table><thead><tr><th>Constraint</th><th>Type argument must be</th><th>Since</th></tr></thead><tbody><tr><td><code>where T : class</code></td><td>A reference type (non-nullable in a nullable context)</td><td>C# 2</td></tr><tr><td><code>where T : class?</code></td><td>A reference type, nullable or not</td><td>C# 8</td></tr><tr><td><code>where T : struct</code></td><td>A non-nullable value type</td><td>C# 2</td></tr><tr><td><code>where T : notnull</code></td><td>A non-nullable value or reference type (warning only)</td><td>C# 8</td></tr><tr><td><code>where T : unmanaged</code></td><td>A struct with no reference fields (int, double, custom structs)</td><td>C# 7.3</td></tr><tr><td><code>where T : new()</code></td><td>Has a public parameterless constructor; must be last</td><td>C# 2</td></tr><tr><td><code>where T : Customer</code></td><td>That base class or a class derived from it</td><td>C# 2</td></tr><tr><td><code>where T : IEntity</code></td><td>Implements that interface (several allowed)</td><td>C# 2</td></tr><tr><td><code>where T : U</code></td><td>The type supplied for U, or one derived from it</td><td>C# 2</td></tr><tr><td><code>where T : allows ref struct</code></td><td>May be a ref struct such as Span<T> (anti-constraint)</td><td>C# 13</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">You can combine them: <code>where T : Customer, IComparable&lt;T&gt;, new()</code>. The order is fixed: <code>class</code>/<code>struct</code>/<code>notnull</code>/<code>unmanaged</code> first, then a base class or interfaces, then <code>new()</code>, then <code>allows ref struct</code>.</p>



<h3 class="wp-block-heading">What Happens When You Break a Constraint</h3>



<p class="wp-block-paragraph">I broke six constraints in one file to collect the real compiler messages. In the screenshot, I piped the run through <code>findstr</code> so only the diagnostic lines show:</p>



<pre class="wp-block-code"><code>#:property PublishAot=false
#nullable enable

var a = new Cache&lt;int&gt;();              // where T : class
var b = new Counter&lt;string&gt;();         // where T : struct
var c = Factory.Create&lt;Invoice&gt;();     // where T : new()
var d = new Buffer&lt;string&gt;();          // where T : unmanaged
var e = new Repository&lt;string&gt;();      // where T : IEntity
var f = new Lookup&lt;string?&gt;();         // where T : notnull

interface IEntity { int Id { get; } }
record Invoice(int Id, decimal Amount) : IEntity;
class Cache&lt;T&gt; where T : class { }
class Counter&lt;T&gt; where T : struct { }
class Buffer&lt;T&gt; where T : unmanaged { }
class Repository&lt;T&gt; where T : IEntity { }
class Lookup&lt;T&gt; where T : notnull { }
static class Factory { public static T Create&lt;T&gt;() where T : new() =&gt; new T(); }</code></pre>



<p class="wp-block-paragraph"><strong>Build output:</strong></p>



<pre class="wp-block-code"><code>ConstraintErrors.cs(4,19): error CS0452: The type &#x27;int&#x27; must be a reference type in order to use it as parameter &#x27;T&#x27; in the generic type or method &#x27;Cache&lt;T&gt;&#x27;
ConstraintErrors.cs(5,21): error CS0453: The type &#x27;string&#x27; must be a non-nullable value type in order to use it as parameter &#x27;T&#x27; in the generic type or method &#x27;Counter&lt;T&gt;&#x27;
ConstraintErrors.cs(6,17): error CS0310: &#x27;Invoice&#x27; must be a non-abstract type with a public parameterless constructor in order to use it as parameter &#x27;T&#x27; in the generic type or method &#x27;Factory.Create&lt;T&gt;()&#x27;
ConstraintErrors.cs(7,20): error CS8377: The type &#x27;string&#x27; must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter &#x27;T&#x27; in the generic type or method &#x27;Buffer&lt;T&gt;&#x27;
ConstraintErrors.cs(8,24): error CS0311: The type &#x27;string&#x27; cannot be used as type parameter &#x27;T&#x27; in the generic type or method &#x27;Repository&lt;T&gt;&#x27;. There is no implicit reference conversion from &#x27;string&#x27; to &#x27;IEntity&#x27;.
ConstraintErrors.cs(9,20): warning CS8714: The type &#x27;string?&#x27; cannot be used as type parameter &#x27;T&#x27; in the generic type or method &#x27;Lookup&lt;T&gt;&#x27;. Nullability of type argument &#x27;string?&#x27; doesn&#x27;t match &#x27;notnull&#x27; constraint.</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1284" height="1142" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-constraints-errors-cs0452-cs0453-cs0310.png" alt="C# generic constraint violations in VS Code: CS0452 class constraint, CS0453 struct constraint, CS0310 new() constraint, unmanaged, interface and notnull errors" class="wp-image-3186" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-constraints-errors-cs0452-cs0453-cs0310.png 1284w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-constraints-errors-cs0452-cs0453-cs0310-300x267.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-constraints-errors-cs0452-cs0453-cs0310-1024x911.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-constraints-errors-cs0452-cs0453-cs0310-768x683.png 768w" sizes="auto, (max-width: 1284px) 100vw, 1284px" /><figcaption class="wp-element-caption">Each broken where clause gets its own compiler error; notnull is only a warning</figcaption></figure>
</div>


<p class="wp-block-paragraph">The ones you&#8217;ll search for most are <code>CS0452</code> (needs a reference type), <code>CS0453</code> (needs a non-nullable value type) and <code>CS0310</code> (needs a public parameterless constructor). The <code>notnull</code> line produced warning <code>CS8714</code>, not an error.</p>



<p class="wp-block-paragraph"><strong>Note:</strong> <code>Invoice</code> failed <code>new()</code> because a positional record only has the constructor with parameters. Add a parameterless constructor or drop the constraint.</p>



<h3 class="wp-block-heading">allows ref struct in C# 13</h3>



<p class="wp-block-paragraph"><code>allows ref struct</code> is the opposite of a constraint: it widens what <code>T</code> may be, so a <code>Span&lt;int&gt;</code> can be the type argument.</p>



<pre class="wp-block-code"><code>#:property PublishAot=false

Span&lt;int&gt; zips = [85004, 78701, 10001];
Console.WriteLine(Describe(zips));
Console.WriteLine(Describe(42));

static string Describe&lt;T&gt;(T value) where T : allows ref struct
    =&gt; typeof(T).Name;</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>Span`1
Int32</code></pre>



<p class="wp-block-paragraph">Remove the clause and the same call stops compiling:</p>



<pre class="wp-block-code"><code>#:property PublishAot=false

Span&lt;int&gt; zips = [85004, 78701, 10001];
Console.WriteLine(Describe(zips));

static string Describe&lt;T&gt;(T value) =&gt; typeof(T).Name;</code></pre>



<p class="wp-block-paragraph"><strong>Build output:</strong></p>



<pre class="wp-block-code"><code>NoAllowsRefStruct.cs(4,19): error CS9244: The type &#x27;Span&lt;int&gt;&#x27; may not be a ref struct or a type parameter allowing ref structs in order to use it as parameter &#x27;T&#x27; in the generic type or method &#x27;Describe&lt;T&gt;(T)&#x27;</code></pre>



<p class="wp-block-paragraph">In exchange, the method can&#8217;t box <code>value</code> or store it in a field, because a ref struct has to stay on the stack.</p>



<h2 class="wp-block-heading">Generic Interfaces: IRepository&lt;T&gt; and IComparable&lt;T&gt;</h2>



<p class="wp-block-paragraph">Interfaces take type parameters too. I split the store into an <code>IRepository&lt;T&gt;</code> contract and an implementation, and let the <code>Invoice</code> record sort itself through <code>IComparable&lt;Invoice&gt;</code>:</p>



<pre class="wp-block-code"><code>#:property PublishAot=false

IRepository&lt;Invoice&gt; repo = new MemoryRepository&lt;Invoice&gt;();
repo.Add(new Invoice(1001, 1249.50m));
repo.Add(new Invoice(1002, 89.99m));
repo.Add(new Invoice(1003, 640.00m));

List&lt;Invoice&gt; sorted = [.. repo.All()];
sorted.Sort();                          // uses IComparable&lt;Invoice&gt;
Console.WriteLine(string.Join(&quot;, &quot;, sorted.Select(i =&gt; i.Id)));

interface IRepository&lt;T&gt; { void Add(T item); IEnumerable&lt;T&gt; All(); }
class MemoryRepository&lt;T&gt; : IRepository&lt;T&gt;
{
    private readonly List&lt;T&gt; _items = [];
    public void Add(T item) =&gt; _items.Add(item);
    public IEnumerable&lt;T&gt; All() =&gt; _items;
}
record Invoice(int Id, decimal Amount) : IComparable&lt;Invoice&gt;
{
    public int CompareTo(Invoice? other) =&gt;
        other is null ? 1 : Amount.CompareTo(other.Amount);
}</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>1002, 1003, 1001</code></pre>



<p class="wp-block-paragraph"><code>List&lt;T&gt;.Sort()</code> called <code>CompareTo</code> and put the invoices in amount order: 1002 ($89.99), 1003, then 1001. The <a href="https://aspdotnethelp.com/interface-in-csharp/">C# interfaces guide</a> covers default members and explicit implementation.</p>



<p class="wp-block-paragraph">In ASP.NET Core, you can register the open type once, <code>AddScoped(typeof(IRepository&lt;&gt;), typeof(MemoryRepository&lt;&gt;))</code>, and the container closes it per request. Picking the lifetime is in my <a href="https://aspdotnethelp.com/dependency-injection-lifetimes-aspnet-core/">DI lifetimes guide</a>.</p>



<h2 class="wp-block-heading">How Do You Restrict C# Generics to Numeric Types?</h2>



<p class="wp-block-paragraph">Use <code>where T : INumber&lt;T&gt;</code> from <code>System.Numerics</code>. It arrived in .NET 7 with C# 11 static abstract interface members, so <code>T.Zero</code>, <code>+</code> and <code>/</code> work on <code>T</code>:</p>



<pre class="wp-block-code"><code>#:property PublishAot=false
using System.Numerics;

int[] units = [12, 30, 8];
decimal[] sales = [1249.50m, 89.99m, 640.00m];
double[] miles = [12.5, 3.25, 40.25];

Console.WriteLine($&quot;Units: {Sum(units)}&quot;);
Console.WriteLine($&quot;Sales: {Sum(sales)}&quot;);
Console.WriteLine($&quot;Miles: {Sum(miles)}&quot;);
Console.WriteLine($&quot;Average sale: {Average(sales):F2}&quot;);

static T Sum&lt;T&gt;(T[] values) where T : INumber&lt;T&gt;
{
    T total = T.Zero;
    foreach (T v in values) total += v;
    return total;
}
static T Average&lt;T&gt;(T[] values) where T : INumber&lt;T&gt;
    =&gt; Sum(values) / T.CreateChecked(values.Length);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>Units: 50
Sales: 1979.49
Miles: 56
Average sale: 659.83</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1284" height="1142" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-math-inumber-sum-int-decimal-double.png" alt="C# generic math Sum&lt;T&gt; where T : INumber&lt;T&gt; adding int, decimal and double arrays with T.Zero, and Average&lt;T&gt; using T.CreateChecked" class="wp-image-3187" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-math-inumber-sum-int-decimal-double.png 1284w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-math-inumber-sum-int-decimal-double-300x267.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-math-inumber-sum-int-decimal-double-1024x911.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generic-math-inumber-sum-int-decimal-double-768x683.png 768w" sizes="auto, (max-width: 1284px) 100vw, 1284px" /><figcaption class="wp-element-caption">One Sum<T> for int, decimal and double, with no overloads</figcaption></figure>
</div>


<p class="wp-block-paragraph">The same method summed 50 units, $1979.49 in sales and 56 miles. <code>T.CreateChecked(values.Length)</code> turns the int count into a <code>T</code> and throws if it doesn&#8217;t fit.</p>



<h2 class="wp-block-heading">Covariance and Contravariance in C# Generics (out T, in T)</h2>



<p class="wp-block-paragraph">Variance answers one question: can a generic of <code>Customer</code> stand in for a generic of <code>Person</code>? Only interfaces and delegates can say yes, through <code>out</code> and <code>in</code>:</p>



<pre class="wp-block-code"><code>#:property PublishAot=false

IEnumerable&lt;Customer&gt; customers = [new(&quot;Jenna Morales&quot;), new(&quot;Tyler Brooks&quot;)];
IEnumerable&lt;Person&gt; people = customers;     // covariance (out T)
Console.WriteLine($&quot;People: {people.Count()}&quot;);

Action&lt;Person&gt; greet = p =&gt; Console.WriteLine($&quot;Hi, {p.Name}&quot;);
Action&lt;Customer&gt; greetCustomer = greet;     // contravariance (in T)
greetCustomer(new Customer(&quot;Marcus Reed&quot;));

object names = new List&lt;string&gt; { &quot;AZ&quot;, &quot;TX&quot; };
object counts = new List&lt;int&gt; { 12, 30 };
Console.WriteLine($&quot;List&lt;string&gt; as IEnumerable&lt;object&gt;: {names is IEnumerable&lt;object&gt;}&quot;);
Console.WriteLine($&quot;List&lt;int&gt; as IEnumerable&lt;object&gt;: {counts is IEnumerable&lt;object&gt;}&quot;);

record Person(string Name);
record Customer(string Name) : Person(Name);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>People: 2
Hi, Marcus Reed
List&lt;string&gt; as IEnumerable&lt;object&gt;: True
List&lt;int&gt; as IEnumerable&lt;object&gt;: False</code></pre>



<p class="wp-block-paragraph"><code>IEnumerable&lt;out T&gt;</code> is covariant and <code>Action&lt;in T&gt;</code> is contravariant, so both assignments compile. <code>List&lt;T&gt;</code> is a class, so it&#8217;s invariant: <code>List&lt;Person&gt; list = new List&lt;Customer&gt;()</code> doesn&#8217;t compile.</p>



<p class="wp-block-paragraph">The last line printed <code>False</code>: variance only works for reference types, so <code>List&lt;int&gt;</code> is not an <code>IEnumerable&lt;object&gt;</code>.</p>



<h2 class="wp-block-heading">default(T) and typeof: Open vs Closed Generic Types</h2>



<p class="wp-block-paragraph"><code>default(T)</code> gives you the zero value of whatever <code>T</code> is, and <code>typeof(List&lt;&gt;)</code> gives the open type with no argument filled in:</p>



<pre class="wp-block-code"><code>#:property PublishAot=false

Console.WriteLine($&quot;int: {Show&lt;int&gt;()}, decimal: {Show&lt;decimal&gt;()}&quot;);
Console.WriteLine($&quot;bool: {Show&lt;bool&gt;()}, string: {Show&lt;string&gt;()}&quot;);

Type open = typeof(List&lt;&gt;);
Type closed = typeof(List&lt;Customer&gt;);
Console.WriteLine($&quot;{open.Name} open: {open.IsGenericTypeDefinition}&quot;);
Console.WriteLine($&quot;{closed.Name} open: {closed.IsGenericTypeDefinition}&quot;);
Console.WriteLine($&quot;Argument: {closed.GetGenericArguments()[0].Name}&quot;);
Type built = open.MakeGenericType(typeof(Invoice));
Console.WriteLine($&quot;Same as List&lt;Invoice&gt;: {built == typeof(List&lt;Invoice&gt;)}&quot;);

static string Show&lt;T&gt;() =&gt; default(T)?.ToString() ?? &quot;null&quot;;
record Customer(string Name);
record Invoice(int Id);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>int: 0, decimal: 0
bool: False, string: null
List`1 open: True
List`1 open: False
Argument: Customer
Same as List&lt;Invoice&gt;: True</code></pre>



<p class="wp-block-paragraph"><code>default</code> is <code>0</code> for numbers, <code>False</code> for bool and <code>null</code> for reference types. Both list types are named <code>List`1</code>, the backtick count of type parameters. <code>MakeGenericType</code> closes an open type at run time.</p>



<h2 class="wp-block-heading">Generic Collections in C#</h2>



<p class="wp-block-paragraph">You&#8217;ll use generics mostly through the built-in collections in <code>System.Collections.Generic</code>. I won&#8217;t repeat them here; they have their own guides:</p>



<ul class="wp-block-list">
<li><code>List&lt;T&gt;</code> for ordered items: <a href="https://aspdotnethelp.com/list-in-csharp/">List in C#</a></li>

<li><code>Dictionary&lt;TKey, TValue&gt;</code> for lookups by key (the one inside <code>Repository&lt;T&gt;</code>)</li>

<li><code>HashSet&lt;T&gt;</code>, <code>Queue&lt;T&gt;</code> and <code>Stack&lt;T&gt;</code> for uniqueness, FIFO and LIFO</li>

<li><code>IEnumerable&lt;T&gt;</code> as the parameter type when a method only reads</li>
</ul>



<h2 class="wp-block-heading">Common C# Generics Mistakes and How to Fix Them</h2>



<p class="wp-block-paragraph">Two bugs I&#8217;ve shipped myself. Same Phoenix strings and records, run on .NET 10:</p>



<pre class="wp-block-code"><code>#:property PublishAot=false
using System.Text;

string s1 = &quot;Phoenix&quot;;
string s2 = new StringBuilder(&quot;Phoenix&quot;).ToString();
Console.WriteLine($&quot;s1 == s2:          {s1 == s2}&quot;);
Console.WriteLine($&quot;SameRef(s1, s2):   {SameRef(s1, s2)}&quot;);
Console.WriteLine($&quot;SameValue(s1, s2): {SameValue(s1, s2)}&quot;);

Counter&lt;Customer&gt;.Count += 2;
Counter&lt;Invoice&gt;.Count += 1;
Console.WriteLine($&quot;Customer: {Counter&lt;Customer&gt;.Count}, Invoice: {Counter&lt;Invoice&gt;.Count}&quot;);

static bool SameRef&lt;T&gt;(T a, T b) where T : class =&gt; a == b;
static bool SameValue&lt;T&gt;(T a, T b) =&gt; EqualityComparer&lt;T&gt;.Default.Equals(a, b);
class Counter&lt;T&gt; { public static int Count; }
record Customer(string Name);
record Invoice(int Id);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>s1 == s2:          True
SameRef(s1, s2):   False
SameValue(s1, s2): True
Customer: 2, Invoice: 1</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1284" height="1142" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generics-mistakes-reference-equality-static-field.png" alt="C# generics mistakes in VS Code: == on T with a class constraint compares references and returns False, EqualityComparer&lt;T&gt;.Default returns True, static field per closed type" class="wp-image-3189" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generics-mistakes-reference-equality-static-field.png 1284w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generics-mistakes-reference-equality-static-field-300x267.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generics-mistakes-reference-equality-static-field-1024x911.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generics-mistakes-reference-equality-static-field-768x683.png 768w" sizes="auto, (max-width: 1284px) 100vw, 1284px" /><figcaption class="wp-element-caption">== on a class-constrained T compares references; each closed type gets its own static field</figcaption></figure>
</div>


<figure class="wp-block-table"><table><thead><tr><th>Mistake</th><th>What happens</th><th>Fix</th></tr></thead><tbody><tr><td><code>a == b</code> with <code>where T : class</code></td><td>Reference comparison, <code>False</code> for equal strings</td><td><code>EqualityComparer&lt;T&gt;.Default.Equals(a, b)</code></td></tr><tr><td>Static field in <code>Counter&lt;T&gt;</code></td><td>One copy per closed type (2 and 1 above)</td><td>Move shared state to a non-generic class</td></tr><tr><td><code>new T()</code> without a constraint</td><td>Compile error</td><td>Add <code>where T : new()</code> last</td></tr><tr><td><code>T?</code> with no constraint</td><td><code>default</code> (0) for value types, not null</td><td>Add <code>where T : struct</code> or <code>class</code></td></tr></tbody></table></figure>



<p class="wp-block-paragraph">If a type parameter only ever gets one argument, I delete it. An <a href="https://aspdotnethelp.com/abstract-class-in-csharp/">abstract base class</a> or plain interface is often the simpler choice.</p>



<h2 class="wp-block-heading">When Should You Use Generics in C#?</h2>



<p class="wp-block-paragraph">My rule: reach for generics when the same logic runs on different types and you&#8217;d otherwise cast or copy code.</p>



<ul class="wp-block-list">
<li>Same algorithm, different element type: a generic method (Largest, Sum).</li>

<li>Same container or wrapper, different payload: a generic class (Repository&lt;T&gt;, Result&lt;T&gt;).</li>

<li>The code needs a member of T: add the narrowest constraint that gives it to you.</li>

<li>You want to add a method to every <code>IEnumerable&lt;T&gt;</code>: a generic extension, now with C# 14 <a href="https://aspdotnethelp.com/extension-members-in-csharp-14/">extension members</a>.</li>
</ul>



<p class="wp-block-paragraph">These pair well with generics:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/csharp-nullable-reference-types/">Nullable reference types in C#</a></li>

<li><a href="https://aspdotnethelp.com/collection-expressions-in-csharp/">Collection expressions in C#</a></li>

<li><a href="https://aspdotnethelp.com/xunit-unit-testing-csharp/">Unit testing C# code with xUnit</a></li>

<li><a href="https://aspdotnethelp.com/learn-csharp/">Learn C# step by step</a></li>
</ul>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-73190000001" class="rank-math-list-item">
<h3 class="rank-math-question ">What are generics in C#?</h3>
<div class="rank-math-answer ">

<p>Generics let a class, interface, method or delegate take a type as a parameter, like <code>List&lt;T&gt;</code>. You write the code once, and the compiler checks types for each use without casts or boxing.</p>

</div>
</div>
<div id="faq-question-73190000002" class="rank-math-list-item">
<h3 class="rank-math-question ">What is the difference between generics and object in C#?</h3>
<div class="rank-math-answer ">

<p>An <code>object</code> parameter accepts anything and needs casts, so mistakes show up at run time and value types get boxed. A generic parameter keeps the real type, so mistakes fail at compile time.</p>

</div>
</div>
<div id="faq-question-73190000003" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I restrict a C# generic to numeric types?</h3>
<div class="rank-math-answer ">

<p>Use <code>where T : INumber&lt;T&gt;</code> from <code>System.Numerics</code> (.NET 7 and later). It allows <code>+</code>, <code>-</code>, <code>T.Zero</code> and comparisons on int, decimal, double and the other built-in numbers.</p>

</div>
</div>
<div id="faq-question-73190000004" class="rank-math-list-item">
<h3 class="rank-math-question ">What does where T : new() mean?</h3>
<div class="rank-math-answer ">

<p>It requires a public parameterless constructor, so the code can call <code>new T()</code>. It must be the last constraint. Microsoft&#8217;s <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters" target="_blank" rel="noopener">constraints on type parameters</a> page lists every rule.</p>

</div>
</div>
<div id="faq-question-73190000005" class="rank-math-list-item">
<h3 class="rank-math-question ">Can a generic class have more than one type parameter?</h3>
<div class="rank-math-answer ">

<p>Yes. Separate them with commas, like <code>Dictionary&lt;TKey, TValue&gt;</code>, and give each its own <code>where</code> clause if it needs one.</p>

</div>
</div>
</div>
</div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Upload Files in ASP.NET Core Web API (IFormFile)</title>
		<link>https://aspdotnethelp.com/upload-files-aspnet-core-web-api/</link>
		
		<dc:creator><![CDATA[Bijay Kumar]]></dc:creator>
		<pubDate>Tue, 01 Dec 2026 15:15:00 +0000</pubDate>
				<category><![CDATA[ASP.NET Core]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=3094</guid>

					<description><![CDATA[For an ASP.NET Core file upload, give a minimal API endpoint an IFormFile parameter, then copy it to disk with CopyToAsync under a random file name: I ran that on .NET 10 and got {"saved":"ejxnpqxa.uj0","length":48209} back. Below, we grow it into a real upload API with multiple files, form fields, size and type checks, and ... <a title="Upload Files in ASP.NET Core Web API (IFormFile)" class="read-more" href="https://aspdotnethelp.com/upload-files-aspnet-core-web-api/" aria-label="Read more about Upload Files in ASP.NET Core Web API (IFormFile)">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">For an <strong>ASP.NET Core file upload</strong>, give a minimal API endpoint an <code>IFormFile</code> parameter, then copy it to disk with <code>CopyToAsync</code> under a random file name:</p>



<pre class="wp-block-code"><code>app.MapPost(&quot;/upload&quot;, async (IFormFile file) =&gt;
{
    string path = Path.Combine(uploadRoot, Path.GetRandomFileName());
    await using FileStream target = File.Create(path);
    await file.CopyToAsync(target);
    return Results.Ok(new { saved = Path.GetFileName(path), file.Length });
}).DisableAntiforgery();</code></pre>



<p class="wp-block-paragraph">I ran that on .NET 10 and got <code>{"saved":"ejxnpqxa.uj0","length":48209}</code> back. Below, we grow it into a real upload API with multiple files, form fields, size and type checks, and streaming for big files.</p>



<h2 class="wp-block-heading">The Finished ASP.NET Core File Upload API</h2>



<p class="wp-block-paragraph">Here&#8217;s what we&#8217;re building. One test script sends every kind of request the API handles, and each line shows the HTTP status it got back:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1292" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-file-upload-api-test-uploads-status-codes-vscode.png" alt="ASP.NET Core file upload API test in VS Code: test-uploads.cmd sends curl.exe -F requests and prints 200 for valid uploads, 400 for a blocked .exe and an oversized PDF, and 413 for a 40 MB file" class="wp-image-3175" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-file-upload-api-test-uploads-status-codes-vscode.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-file-upload-api-test-uploads-status-codes-vscode-300x280.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-file-upload-api-test-uploads-status-codes-vscode-1024x956.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-file-upload-api-test-uploads-status-codes-vscode-768x717.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">The finished API: valid files get 200, bad ones get 400 or 413</figcaption></figure>
</div>


<ul class="wp-block-list">
<li><code>/api/uploads/single</code> takes one <code>IFormFile</code> and saves it outside the project.</li>

<li><code>/many</code> and <code>/photos</code> take several files through <code>IFormFileCollection</code>.</li>

<li><code>/vendor</code> binds a file plus text fields into a <code>[FromForm]</code> record.</li>

<li><code>/stream</code> reads a 40 MB file with <code>MultipartReader</code> instead of buffering it.</li>
</ul>



<h2 class="wp-block-heading">Before You Start: Sample Upload Files</h2>



<p class="wp-block-paragraph">You need the .NET 10 SDK (I used 10.0.402), VS Code and curl.exe, which ships with Windows 10 and 11. I made eight sample files with real file signatures and dummy content:</p>



<figure class="wp-block-table"><table><thead><tr><th>Sample file</th><th>Size</th><th>What it tests</th></tr></thead><tbody><tr><td>invoice-2026-11.pdf</td><td>48 KB</td><td>a normal single upload</td></tr><tr><td>headshot.jpg, storefront.png</td><td>116 KB, 84 KB</td><td>multiple files</td></tr><tr><td>w9-brooks-roofing.pdf</td><td>60 KB</td><td>a file plus form fields</td></tr><tr><td>payroll-macro.exe</td><td>23 KB</td><td>a blocked extension</td></tr><tr><td>statement.pdf</td><td>23 KB</td><td>an .exe renamed to .pdf</td></tr><tr><td>scan-6mb.pdf</td><td>6.0 MB</td><td>the app&#8217;s 5 MB limit</td></tr><tr><td>site-plans-40mb.pdf</td><td>40 MB</td><td>Kestrel&#8217;s limit and streaming</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">Step 1: Create the W13UploadApi Project</h2>



<p class="wp-block-paragraph">Start from the empty web template, not the Web API one, since we don&#8217;t need the weather sample:</p>



<pre class="wp-block-code"><code>dotnet new web -n W13UploadApi -o W13UploadApi</code></pre>



<p class="wp-block-paragraph">I deleted appsettings.Development.json and the Properties folder, and I start the API with <code>dotnet run -- --urls http://localhost:5910 --environment Development</code>. The project file is the template&#8217;s own:</p>



<pre class="wp-block-code"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
  &lt;/PropertyGroup&gt;

&lt;/Project&gt;</code></pre>



<p class="wp-block-paragraph">Add an Uploads section to <code>appsettings.json</code>. The folder sits next to the project, not inside it, and the size cap is 5 MB:</p>



<pre class="wp-block-code"><code>{
  &quot;Logging&quot;: {
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Information&quot;,
      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;
    }
  },
  &quot;AllowedHosts&quot;: &quot;*&quot;,
  &quot;Uploads&quot;: {
    &quot;Root&quot;: &quot;C:\\DotNetDemo\\W13UploadApi\\uploads&quot;,
    &quot;MaxBytes&quot;: 5242880
  }
}</code></pre>



<p class="wp-block-paragraph"><strong>Checkpoint:</strong> <code>dotnet build</code> succeeds. If the folder differs per machine, move it into <a href="https://aspdotnethelp.com/appsettings-per-environment-aspnet-core/">appsettings per environment</a>.</p>



<h2 class="wp-block-heading">Step 2: Write the UploadStore Class</h2>



<p class="wp-block-paragraph">All the file handling lives in one class, so every endpoint saves and checks files the same way. Add <code>UploadStore.cs</code>:</p>



<pre class="wp-block-code"><code>namespace W13UploadApi;

public record SavedFile(string Saved, string Original, long Size, string ContentType);

public class UploadStore(IConfiguration config)
{
    static readonly Dictionary&lt;string, (string Type, byte[] Magic)&gt; Allowed = new()
    {
        [&quot;.pdf&quot;] = (&quot;application/pdf&quot;, &quot;%PDF&quot;u8.ToArray()),
        [&quot;.jpg&quot;] = (&quot;image/jpeg&quot;, [0xFF, 0xD8, 0xFF]),
        [&quot;.png&quot;] = (&quot;image/png&quot;, [0x89, 0x50, 0x4E, 0x47]),
    };
    public string Root { get; } = config[&quot;Uploads:Root&quot;]!;
    readonly long maxBytes = config.GetValue&lt;long&gt;(&quot;Uploads:MaxBytes&quot;);

    public string? Validate(IFormFile file)
    {
        string ext = Path.GetExtension(file.FileName).ToLowerInvariant();
        if (file.Length == 0) return &quot;The file is empty.&quot;;
        if (file.Length &gt; maxBytes) return $&quot;The file is {file.Length / 1048576.0:0.0} MB; the limit is {maxBytes / 1048576} MB.&quot;;
        if (!Allowed.TryGetValue(ext, out var rule)) return $&quot;{ext} files aren&#x27;t allowed.&quot;;
        if (file.ContentType != rule.Type) return $&quot;Content-Type {file.ContentType} doesn&#x27;t match {ext}.&quot;;

        byte[] head = new byte[rule.Magic.Length];
        using Stream stream = file.OpenReadStream();
        stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false);
        return head.SequenceEqual(rule.Magic) ? null : $&quot;The content isn&#x27;t a real {ext} file.&quot;;
    }

    public async Task&lt;SavedFile&gt; SaveAsync(IFormFile file, CancellationToken ct = default)
    {
        Directory.CreateDirectory(Root);
        string ext = Path.GetExtension(file.FileName).ToLowerInvariant();
        string name = Path.ChangeExtension(Path.GetRandomFileName(), ext);   // never the client&#x27;s name
        await using FileStream target = File.Create(Path.Combine(Root, name));
        await file.CopyToAsync(target, ct);
        return new(name, Path.GetFileName(file.FileName), file.Length, file.ContentType);
    }
}</code></pre>



<p class="wp-block-paragraph"><code>SaveAsync</code> never uses the client&#8217;s file name on disk. <code>Path.GetRandomFileName</code> makes the name, and the original goes through <code>Path.GetFileName</code>, so a name like ..\..\web.config loses its path before it&#8217;s even logged.</p>



<p class="wp-block-paragraph"><code>Validate</code> returns an error message or <code>null</code>. The class reads its settings through a <a href="https://aspdotnethelp.com/primary-constructors-in-csharp/">primary constructor</a>.</p>



<h2 class="wp-block-heading">Step 3: Upload a Single File with IFormFile</h2>



<p class="wp-block-paragraph">Each group of endpoints gets its own file. <code>Endpoints/SingleFile.cs</code> maps POST /single:</p>



<pre class="wp-block-code"><code>namespace W13UploadApi.Endpoints;

public static class SingleFile
{
    public static RouteGroupBuilder MapSingleFile(this RouteGroupBuilder api)
    {
        api.MapPost(&quot;/single&quot;, async (IFormFile file, UploadStore store) =&gt;
            store.Validate(file) is string error
                ? Results.BadRequest(new { error })
                : Results.Ok(await store.SaveAsync(file)));
        return api;
    }
}</code></pre>



<p class="wp-block-paragraph">The parameter name <code>file</code> has to match the form field name. Then wire it up in <code>Program.cs</code>:</p>



<pre class="wp-block-code"><code>using W13UploadApi;
using W13UploadApi.Endpoints;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton&lt;UploadStore&gt;();

var app = builder.Build();

RouteGroupBuilder api = app.MapGroup(&quot;/api/uploads&quot;);
api.MapSingleFile();

app.Run();</code></pre>



<p class="wp-block-paragraph">Run the API and send the invoice with curl. The findstr filter keeps the status line and the exception message:</p>



<pre class="wp-block-code"><code>curl.exe -s -i -F &quot;file=@samples/invoice-2026-11.pdf&quot; http://localhost:5910/api/uploads/single | findstr /c:&quot;HTTP/1.1&quot; /c:&quot;InvalidOperationException&quot;</code></pre>



<p class="wp-block-paragraph"><strong>Output</strong> (stack trace trimmed):</p>



<pre class="wp-block-code"><code>HTTP/1.1 500 Internal Server Error
Content-Type: text/plain; charset=utf-8

System.InvalidOperationException: Endpoint HTTP: POST /api/uploads/single contains anti-forgery metadata, but a middleware was not found that supports anti-forgery.</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1292" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/iformfile-minimal-api-antiforgery-middleware-not-found-500-error.png" alt="IFormFile minimal API in VS Code: Program.cs maps the upload group and curl.exe gets HTTP 500 InvalidOperationException, endpoint contains anti-forgery metadata but a middleware was not found that supports anti-forgery" class="wp-image-3179" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/iformfile-minimal-api-antiforgery-middleware-not-found-500-error.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/iformfile-minimal-api-antiforgery-middleware-not-found-500-error-300x280.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/iformfile-minimal-api-antiforgery-middleware-not-found-500-error-1024x956.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/iformfile-minimal-api-antiforgery-middleware-not-found-500-error-768x717.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">The first run fails: IFormFile endpoints carry antiforgery metadata</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Checkpoint:</strong> a 500, and that&#8217;s expected. Since .NET 8, minimal API endpoints that bind form data (<code>IFormFile</code>, <code>[FromForm]</code>) require antiforgery validation, and the web template has no antiforgery middleware.</p>



<h2 class="wp-block-heading">Step 4: Fix the IFormFile Antiforgery Error with DisableAntiforgery()</h2>



<p class="wp-block-paragraph">An API that callers reach with curl, a mobile app or a bearer token isn&#8217;t a CSRF target, because there&#8217;s no cookie for a forged form to ride on. So opt the group out:</p>



<pre class="wp-block-code"><code>RouteGroupBuilder api = app.MapGroup(&quot;/api/uploads&quot;)
    .DisableAntiforgery();              // API callers send bearer tokens, not cookies</code></pre>



<p class="wp-block-paragraph">That replaces the MapGroup line in Program.cs. Send the invoice again, this time without the filter:</p>



<pre class="wp-block-code"><code>curl.exe -i -F &quot;file=@samples/invoice-2026-11.pdf&quot; http://localhost:5910/api/uploads/single</code></pre>



<pre class="wp-block-code"><code>HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{
  &quot;saved&quot;: &quot;1pxukcj3.pdf&quot;,
  &quot;original&quot;: &quot;invoice-2026-11.pdf&quot;,
  &quot;size&quot;: 48209,
  &quot;contentType&quot;: &quot;application/pdf&quot;
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1292" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/iformfile-single-file-upload-minimal-api-curl-200-response.png" alt="Upload a single file in ASP.NET Core with IFormFile: SingleFile.cs maps POST /single and curl.exe -F returns 200 OK with the saved random file name, the original invoice-2026-11.pdf and its size" class="wp-image-3180" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/iformfile-single-file-upload-minimal-api-curl-200-response.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/iformfile-single-file-upload-minimal-api-curl-200-response-300x280.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/iformfile-single-file-upload-minimal-api-curl-200-response-1024x956.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/iformfile-single-file-upload-minimal-api-curl-200-response-768x717.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">With DisableAntiforgery(), the single upload returns 200</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Checkpoint:</strong> 200 OK, saved as <code>1pxukcj3.pdf</code>, with the original name only in the response. Your random name will differ.</p>



<p class="wp-block-paragraph">If the same app serves Razor Pages or Blazor forms, keep antiforgery for those and opt out only here. With <code>AddAntiforgery()</code> and <code>UseAntiforgery()</code> but no opt-out, curl gets a 400 instead:</p>



<pre class="wp-block-code"><code>HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8

Microsoft.AspNetCore.Http.BadHttpRequestException: Invalid anti-forgery token found when reading parameter &quot;IFormFile file&quot; from the request body as form.</code></pre>



<p class="wp-block-paragraph">Protect the API with tokens instead; I set that up in <a href="https://aspdotnethelp.com/jwt-authentication-aspnet-core/">JWT authentication in ASP.NET Core</a>.</p>



<h2 class="wp-block-heading">Step 5: Upload Multiple Files with IFormFileCollection</h2>



<p class="wp-block-paragraph">For several files, bind <code>IFormFileCollection</code>. It holds every file in the form, whatever the field names. Add <code>Endpoints/MultipleFiles.cs</code>:</p>



<pre class="wp-block-code"><code>namespace W13UploadApi.Endpoints;

public static class MultipleFiles
{
    public static RouteGroupBuilder MapMultipleFiles(this RouteGroupBuilder api)
    {
        // every file in the form, whatever its field name
        api.MapPost(&quot;/many&quot;, async (IFormFileCollection files, UploadStore store) =&gt;
        {
            var errors = files.Where(f =&gt; store.Validate(f) is not null)
                .Select(f =&gt; $&quot;{f.FileName}: {store.Validate(f)}&quot;).ToList();
            if (errors.Count &gt; 0) return Results.BadRequest(new { errors });

            var saved = new List&lt;SavedFile&gt;();
            foreach (IFormFile file in files) saved.Add(await store.SaveAsync(file));
            return Results.Ok(saved);
        });

        // only the files sent in fields named &quot;photos&quot;
        api.MapPost(&quot;/photos&quot;, (IFormFileCollection files) =&gt;
        {
            IReadOnlyList&lt;IFormFile&gt; photos = files.GetFiles(&quot;photos&quot;);
            return Results.Ok(new { received = photos.Count, names = photos.Select(p =&gt; p.FileName) });
        });
        return api;
    }
}</code></pre>



<p class="wp-block-paragraph">Add <code>api.MapMultipleFiles();</code> to Program.cs, then send three files in one request:</p>



<pre class="wp-block-code"><code>curl.exe -i -F &quot;files=@samples/invoice-2026-11.pdf&quot; -F &quot;files=@samples/headshot.jpg&quot; -F &quot;files=@samples/storefront.png&quot; http://localhost:5910/api/uploads/many</code></pre>



<pre class="wp-block-code"><code>HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

[
  {
    &quot;saved&quot;: &quot;nudgqqx5.pdf&quot;,
    &quot;original&quot;: &quot;invoice-2026-11.pdf&quot;,
    &quot;size&quot;: 48209,
    &quot;contentType&quot;: &quot;application/pdf&quot;
  },
  {
    &quot;saved&quot;: &quot;nymvhshj.jpg&quot;,
    &quot;original&quot;: &quot;headshot.jpg&quot;,
    &quot;size&quot;: 118404,
    &quot;contentType&quot;: &quot;image/jpeg&quot;
  },
  {
    &quot;saved&quot;: &quot;pwyrk5sc.png&quot;,
    &quot;original&quot;: &quot;storefront.png&quot;,
    &quot;size&quot;: 86308,
    &quot;contentType&quot;: &quot;image/png&quot;
  }
]</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1292" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-upload-multiple-files-iformfilecollection-curl.png" alt="Upload multiple files in ASP.NET Core: MultipleFiles.cs binds IFormFileCollection and curl.exe sends invoice-2026-11.pdf, headshot.jpg and storefront.png, getting three saved files back" class="wp-image-3178" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-upload-multiple-files-iformfilecollection-curl.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-upload-multiple-files-iformfilecollection-curl-300x280.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-upload-multiple-files-iformfilecollection-curl-1024x956.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-upload-multiple-files-iformfilecollection-curl-768x717.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">Three files in, three random names out</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Checkpoint:</strong> an array of three saved files. The endpoint validates all of them before it saves any, so one bad file doesn&#8217;t leave half a batch on disk.</p>



<p class="wp-block-paragraph">When only one field matters, filter by name with <code>GetFiles</code>. I sent two photos fields plus an invoice field to <code>/photos</code>:</p>



<pre class="wp-block-code"><code>{
  &quot;received&quot;: 2,
  &quot;names&quot;: [
    &quot;headshot.jpg&quot;,
    &quot;storefront.png&quot;
  ]
}</code></pre>



<p class="wp-block-paragraph"><strong>Important:</strong> Microsoft Learn&#8217;s binding table lists <code>IReadOnlyList&lt;IFormFile&gt;</code> as supported, matched by field name. On .NET 10.0.13 it didn&#8217;t work for me: without <code>[FromForm]</code> it returned 415 Unsupported Media Type, and with <code>[FromForm]</code> it bound an empty list (<code>received: 0</code>).</p>



<p class="wp-block-paragraph"><code>List&lt;IFormFile&gt;</code> also got a 415, because the minimal API read it as a JSON body. Stick with <code>IFormFileCollection</code> plus <code>GetFiles</code> until that changes.</p>



<h2 class="wp-block-heading">Step 6: Send Form Fields with the File Using [FromForm]</h2>



<p class="wp-block-paragraph">A vendor portal needs the W-9 plus who sent it. Put the text fields and the file in one record and mark the parameter <code>[FromForm]</code>. Add <code>Endpoints/FormFields.cs</code>:</p>



<pre class="wp-block-code"><code>using Microsoft.AspNetCore.Mvc;

namespace W13UploadApi.Endpoints;

public record VendorDocument(string VendorName, string State, IFormFile File);

public static class FormFields
{
    public static RouteGroupBuilder MapFormFields(this RouteGroupBuilder api)
    {
        api.MapPost(&quot;/vendor&quot;, async ([FromForm] VendorDocument doc, UploadStore store) =&gt;
        {
            if (store.Validate(doc.File) is string error) return Results.BadRequest(new { error });
            SavedFile saved = await store.SaveAsync(doc.File);
            return Results.Ok(new { doc.VendorName, doc.State, saved.Saved, saved.Size });
        });
        return api;
    }
}</code></pre>



<p class="wp-block-paragraph">Add <code>api.MapFormFields();</code> to Program.cs and post two text fields with the PDF:</p>



<pre class="wp-block-code"><code>curl.exe -i -F &quot;vendorName=Brooks Roofing LLC&quot; -F &quot;state=TX&quot; -F &quot;file=@samples/w9-brooks-roofing.pdf&quot; http://localhost:5910/api/uploads/vendor</code></pre>



<pre class="wp-block-code"><code>HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{
  &quot;vendorName&quot;: &quot;Brooks Roofing LLC&quot;,
  &quot;state&quot;: &quot;TX&quot;,
  &quot;saved&quot;: &quot;kohrhequ.pdf&quot;,
  &quot;size&quot;: 61709
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1292" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/minimal-api-fromform-record-iformfile-form-fields-upload.png" alt="Minimal API [FromForm] record with IFormFile in VS Code: FormFields.cs binds VendorDocument and curl.exe sends vendorName Brooks Roofing LLC, state TX and the W-9 PDF, returning 200" class="wp-image-3181" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/minimal-api-fromform-record-iformfile-form-fields-upload.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/minimal-api-fromform-record-iformfile-form-fields-upload-300x280.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/minimal-api-fromform-record-iformfile-form-fields-upload-1024x956.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/minimal-api-fromform-record-iformfile-form-fields-upload-768x717.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">One record, two text fields and a file</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Checkpoint:</strong> Brooks Roofing LLC, TX and the saved name come back together. The lowercase field names matched the record&#8217;s properties. To check the text fields too, add the rules from <a href="https://aspdotnethelp.com/minimal-api-validation-aspnet-core/">minimal API validation</a>.</p>



<h2 class="wp-block-heading">Step 7: Validate File Size, Extension and Content Type</h2>



<p class="wp-block-paragraph">Now the UploadStore checks from Step 2 earn their keep. I sent four bad files to /single:</p>



<pre class="wp-block-code"><code>curl.exe -s -w &quot; -&gt; %{http_code}\n&quot; -F &quot;file=@samples/payroll-macro.exe&quot; http://localhost:5910/api/uploads/single
curl.exe -s -w &quot; -&gt; %{http_code}\n&quot; -F &quot;file=@samples/statement.pdf&quot; http://localhost:5910/api/uploads/single
curl.exe -s -w &quot; -&gt; %{http_code}\n&quot; -F &quot;file=@samples/scan-6mb.pdf&quot; http://localhost:5910/api/uploads/single
curl.exe -s -w &quot; -&gt; %{http_code}\n&quot; -F &quot;file=@samples/site-plans-40mb.pdf&quot; http://localhost:5910/api/uploads/single</code></pre>



<pre class="wp-block-code"><code>{&quot;error&quot;:&quot;.exe files aren&#x27;t allowed.&quot;} -&gt; 400
{&quot;error&quot;:&quot;The content isn&#x27;t a real .pdf file.&quot;} -&gt; 400
{&quot;error&quot;:&quot;The file is 6.0 MB; the limit is 5 MB.&quot;} -&gt; 400
 -&gt; 413</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1292" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-file-upload-validation-extension-signature-size-413.png" alt="ASP.NET Core file upload validation in VS Code: UploadStore.cs checks extension, content type and file signature; curl.exe gets 400 for payroll-macro.exe, a renamed statement.pdf and a 6 MB scan, and 413 for a 40 MB PDF" class="wp-image-3176" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-file-upload-validation-extension-signature-size-413.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-file-upload-validation-extension-signature-size-413-300x280.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-file-upload-validation-extension-signature-size-413-1024x956.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-file-upload-validation-extension-signature-size-413-768x717.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">Three 400s from the app, one 413 from Kestrel</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Checkpoint:</strong> 400, 400, 400, 413. The renamed .exe passed the extension and content-type checks; only the file signature (the first bytes, %PDF for a PDF) caught it. The <code>Content-Type</code> comes from the client, so never trust it alone.</p>



<p class="wp-block-paragraph">The 40 MB file never reached my code. Kestrel rejected the body, and these settings decide where that happens:</p>



<figure class="wp-block-table"><table><thead><tr><th>Limit</th><th>Default</th><th>Set it with</th></tr></thead><tbody><tr><td>Kestrel MaxRequestBodySize</td><td>30,000,000 bytes (~28.6 MB)</td><td><code>ConfigureKestrel</code>, or <code>[RequestSizeLimit]</code> per endpoint</td></tr><tr><td>FormOptions.MultipartBodyLengthLimit</td><td>134,217,728 bytes (128 MB)</td><td><code>Configure&lt;FormOptions&gt;</code>, or <code>[RequestFormLimits]</code></td></tr><tr><td>FormOptions.MemoryBufferThreshold</td><td>64 KB</td><td>larger buffered files go to a temp file</td></tr><tr><td>UploadStore check</td><td>5 MB here</td><td>appsettings.json</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Raise the server limits only for the endpoints that need them, as Step 8 does. If your clients expect problem details for the 400s, shape them with <a href="https://aspdotnethelp.com/aspnet-core-global-error-handling/">global error handling</a>.</p>



<h2 class="wp-block-heading">Step 8: Stream Large Files with MultipartReader</h2>



<p class="wp-block-paragraph">An <code>IFormFile</code> is buffered: the whole file sits in memory or a temp file before your code runs. For big files, read the body yourself, one section at a time. Add <code>Endpoints/Streaming.cs</code>:</p>



<pre class="wp-block-code"><code>using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;

namespace W13UploadApi.Endpoints;

public static class Streaming
{
    public static RouteGroupBuilder MapStreaming(this RouteGroupBuilder api)
    {
        api.MapPost(&quot;/stream&quot;, async (HttpRequest request, UploadStore store) =&gt;
        {
            string boundary = HeaderUtilities.RemoveQuotes(
                MediaTypeHeaderValue.Parse(request.ContentType).Boundary).Value!;
            var reader = new MultipartReader(boundary, request.Body);
            var saved = new List&lt;object&gt;();

            while (await reader.ReadNextSectionAsync() is { } section)
            {
                if (section.AsFileSection() is not { FileStream: not null } file) continue;
                string name = Path.ChangeExtension(Path.GetRandomFileName(), Path.GetExtension(file.FileName));
                await using FileStream target = File.Create(Path.Combine(store.Root, name));
                await file.FileStream.CopyToAsync(target);      // 64 KB at a time, never the whole file
                saved.Add(new { saved = name, original = file.FileName, size = target.Length });
            }
            return Results.Ok(saved);
        }).WithMetadata(new RequestSizeLimitAttribute(200_000_000));
        return api;
    }
}</code></pre>



<p class="wp-block-paragraph">Add <code>api.MapStreaming();</code> to Program.cs. The <code>RequestSizeLimitAttribute</code> metadata raises Kestrel&#8217;s limit to 200 MB for this endpoint only. Then send the same 40 MB file that got a 413:</p>



<pre class="wp-block-code"><code>curl.exe -i -F &quot;file=@samples/site-plans-40mb.pdf&quot; http://localhost:5910/api/uploads/stream</code></pre>



<pre class="wp-block-code"><code>HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

[
  {
    &quot;saved&quot;: &quot;a55ppefj.pdf&quot;,
    &quot;original&quot;: &quot;site-plans-40mb.pdf&quot;,
    &quot;size&quot;: 41900009
  }
]</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1292" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-multipartreader-stream-large-file-upload-40mb.png" alt="Stream a large file upload in ASP.NET Core: Streaming.cs reads Request.Body with MultipartReader and curl.exe uploads site-plans-40mb.pdf, saved with 41,900,009 bytes and 200 OK" class="wp-image-3177" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-multipartreader-stream-large-file-upload-40mb.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-multipartreader-stream-large-file-upload-40mb-300x280.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-multipartreader-stream-large-file-upload-40mb-1024x956.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-multipartreader-stream-large-file-upload-40mb-768x717.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">The 40 MB file that /single refused, streamed to disk</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Checkpoint:</strong> 200 OK and 41,900,009 bytes on disk. Streaming doesn&#8217;t make uploads faster; it keeps big files out of memory and temp files. Add the signature checks here too before you ship it.</p>



<h2 class="wp-block-heading">Test the Upload API with curl.exe</h2>



<p class="wp-block-paragraph">Here&#8217;s the script from the top of the post, <code>test-uploads.cmd</code>, in the folder above the project. The <code>%%</code> escapes the percent sign inside a batch file:</p>



<pre class="wp-block-code"><code>@echo off
rem One request per endpoint: HTTP status, route, what was sent
set API=http://localhost:5910/api/uploads
curl.exe -s -o NUL -w &quot;%%{http_code}  /single     invoice-2026-11.pdf\n&quot; -F &quot;file=@samples/invoice-2026-11.pdf&quot; %API%/single
curl.exe -s -o NUL -w &quot;%%{http_code}  /many       3 files\n&quot; -F &quot;files=@samples/invoice-2026-11.pdf&quot; -F &quot;files=@samples/headshot.jpg&quot; -F &quot;files=@samples/storefront.png&quot; %API%/many
curl.exe -s -o NUL -w &quot;%%{http_code}  /photos     2 photos + 1 invoice\n&quot; -F &quot;photos=@samples/headshot.jpg&quot; -F &quot;photos=@samples/storefront.png&quot; -F &quot;invoice=@samples/invoice-2026-11.pdf&quot; %API%/photos
curl.exe -s -o NUL -w &quot;%%{http_code}  /vendor     W-9 + vendorName + state\n&quot; -F &quot;vendorName=Brooks Roofing LLC&quot; -F &quot;state=TX&quot; -F &quot;file=@samples/w9-brooks-roofing.pdf&quot; %API%/vendor
curl.exe -s -o NUL -w &quot;%%{http_code}  /single     payroll-macro.exe\n&quot; -F &quot;file=@samples/payroll-macro.exe&quot; %API%/single
curl.exe -s -o NUL -w &quot;%%{http_code}  /single     statement.pdf (an .exe inside)\n&quot; -F &quot;file=@samples/statement.pdf&quot; %API%/single
curl.exe -s -o NUL -w &quot;%%{http_code}  /single     scan-6mb.pdf\n&quot; -F &quot;file=@samples/scan-6mb.pdf&quot; %API%/single
curl.exe -s -o NUL -w &quot;%%{http_code}  /single     site-plans-40mb.pdf\n&quot; -F &quot;file=@samples/site-plans-40mb.pdf&quot; %API%/single
curl.exe -s -o NUL -w &quot;%%{http_code}  /stream     site-plans-40mb.pdf\n&quot; -F &quot;file=@samples/site-plans-40mb.pdf&quot; %API%/stream
curl.exe -s -o NUL -w &quot;%%{http_code}  /documents  headshot.jpg (controller)\n&quot; -F &quot;file=@samples/headshot.jpg&quot; http://localhost:5910/api/documents</code></pre>



<p class="wp-block-paragraph">With the API running, I ran <code>.\test-uploads.cmd</code> from a Command Prompt in that folder. <strong>Output:</strong></p>



<pre class="wp-block-code"><code>200  /single     invoice-2026-11.pdf
200  /many       3 files
200  /photos     2 photos + 1 invoice
200  /vendor     W-9 + vendorName + state
400  /single     payroll-macro.exe
400  /single     statement.pdf (an .exe inside)
400  /single     scan-6mb.pdf
413  /single     site-plans-40mb.pdf
200  /stream     site-plans-40mb.pdf
200  /documents  headshot.jpg (controller)</code></pre>



<p class="wp-block-paragraph">Every valid file got 200 and every bad one was stopped. If you&#8217;d rather click than type, publish an OpenAPI document and browse the endpoints in Scalar, as in <a href="https://aspdotnethelp.com/openapi-scalar-aspnet-core/">OpenAPI and Scalar in ASP.NET Core</a>. Then I listed the uploads folder:</p>



<pre class="wp-block-code"><code>02gj1nuf.pdf
3fzbxwrc.pdf
5k3vcugg.pdf
ailvpwrs.png
fxwikydv.jpg
pcuh3jwi.pdf
wgsbjoa0.jpg</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1292" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/uploads-folder-random-file-names-outside-project-dir.png" alt="Uploads folder listing in the VS Code terminal: dir /b uploads shows seven random file names saved by UploadStore outside the W13UploadApi project folder" class="wp-image-3183" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/uploads-folder-random-file-names-outside-project-dir.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/uploads-folder-random-file-names-outside-project-dir-300x280.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/uploads-folder-random-file-names-outside-project-dir-1024x956.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/uploads-folder-random-file-names-outside-project-dir-768x717.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">Seven saved files, none with the client&#8217;s name</figcaption></figure>
</div>


<p class="wp-block-paragraph">Seven random names and no client file names. The rejected files were never written.</p>



<h2 class="wp-block-heading">Same Upload with an [ApiController] Controller</h2>



<p class="wp-block-paragraph">If your API uses controllers, the code barely changes. <code>[ApiController]</code> infers <code>[FromForm]</code> for <code>IFormFile</code>, and my controller upload worked without any antiforgery opt-out. Add <code>Controllers/DocumentsController.cs</code>:</p>



<pre class="wp-block-code"><code>using Microsoft.AspNetCore.Mvc;

namespace W13UploadApi.Controllers;

[ApiController]
[Route(&quot;api/documents&quot;)]
public class DocumentsController(UploadStore store) : ControllerBase
{
    [HttpPost]
    [RequestSizeLimit(10_000_000)]
    public async Task&lt;IActionResult&gt; Upload(IFormFile file)
    {
        if (store.Validate(file) is string error) return BadRequest(new { error });
        return Ok(await store.SaveAsync(file));
    }
}</code></pre>



<p class="wp-block-paragraph">Two lines in <code>Program.cs</code> turn controllers on. Here&#8217;s the finished file:</p>



<pre class="wp-block-code"><code>using W13UploadApi;
using W13UploadApi.Endpoints;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton&lt;UploadStore&gt;();
builder.Services.AddControllers();

var app = builder.Build();

RouteGroupBuilder api = app.MapGroup(&quot;/api/uploads&quot;)
    .DisableAntiforgery();              // API callers send bearer tokens, not cookies
api.MapSingleFile();
api.MapMultipleFiles();
api.MapFormFields();
api.MapStreaming();
app.MapControllers();

app.Run();</code></pre>



<p class="wp-block-paragraph">The headshot returned 200 from /api/documents. The 40 MB PDF hit the action&#8217;s 10 MB <code>[RequestSizeLimit]</code> and came back as a 400 with problem details, not a bare 413:</p>



<pre class="wp-block-code"><code>{
  &quot;type&quot;: &quot;https://tools.ietf.org/html/rfc9110#section-15.5.1&quot;,
  &quot;title&quot;: &quot;One or more validation errors occurred.&quot;,
  &quot;status&quot;: 400,
  &quot;errors&quot;: {
    &quot;&quot;: [
      &quot;Failed to read the request form. Request body too large. The max request body size is 10000000 bytes.&quot;
    ]
  },
  &quot;traceId&quot;: &quot;00-c551d1072...&quot;
}</code></pre>



<p class="wp-block-paragraph">I compare the two styles in <a href="https://aspdotnethelp.com/minimal-api-vs-controllers-aspnet-core/">minimal APIs vs controllers</a>.</p>



<h2 class="wp-block-heading">Why Does My ASP.NET Core File Upload Fail?</h2>



<p class="wp-block-paragraph"><strong>500, contains anti-forgery metadata.</strong> The endpoint binds a form and nothing handles antiforgery. Call <code>DisableAntiforgery()</code> for token-based APIs, or <code>UseAntiforgery()</code> plus a real token for browser forms.</p>



<p class="wp-block-paragraph"><strong>400, required parameter was not provided.</strong> The form field name doesn&#8217;t match the parameter. I sent the file as <code>document</code> instead of <code>file</code>:</p>



<pre class="wp-block-code"><code>HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8

Microsoft.AspNetCore.Http.BadHttpRequestException: Required parameter &quot;IFormFile file&quot; was not provided from form file.</code></pre>



<p class="wp-block-paragraph"><strong>415 Unsupported Media Type.</strong> You sent JSON to a form endpoint, or used <code>List&lt;IFormFile&gt;</code> in a minimal API. Send multipart/form-data (<code>curl -F</code>) and bind <code>IFormFileCollection</code>.</p>



<p class="wp-block-paragraph"><strong>413 Payload Too Large.</strong> That&#8217;s Kestrel&#8217;s 30,000,000-byte limit; raise it per endpoint or stream as in Step 8. On IIS, the <code>maxAllowedContentLength</code> setting in web.config applies too.</p>



<p class="wp-block-paragraph"><strong>Note:</strong> a browser page on another origin also needs CORS to post files; see <a href="https://aspdotnethelp.com/cors-in-aspnet-core/">CORS in ASP.NET Core</a>. Learn lists a file path as the request body among the features the Visual Studio .http editor doesn&#8217;t support, so test uploads with curl.exe.</p>



<h2 class="wp-block-heading">Where to Take It Next</h2>



<p class="wp-block-paragraph">To keep files in the cloud instead of on the web server, swap the <code>FileStream</code> in <code>SaveAsync</code> for a blob upload; my <a href="https://aspdotnethelp.com/azure-blob-storage-csharp/">Azure Blob Storage in C# guide</a> shows the client code.</p>



<p class="wp-block-paragraph">To record who uploaded what, save the random name, original name and size in a table, as in <a href="https://aspdotnethelp.com/aspnet-core-web-api-crud-ef-core/">the Web API CRUD with EF Core build</a>.</p>



<p class="wp-block-paragraph">A few more posts that fit this build:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/asp-net-core-tutorials/">All ASP.NET Core tutorials on AspDotnetHelp</a></li>

<li><a href="https://aspdotnethelp.com/cancellationtoken-in-csharp/">CancellationToken in C#, for uploads the client abandons</a></li>

<li><a href="https://aspdotnethelp.com/aspnet-core-middleware/">ASP.NET Core middleware, where antiforgery runs</a></li>

<li><a href="https://aspdotnethelp.com/options-pattern-aspnet-core/">The options pattern, a typed home for the Uploads settings</a></li>
</ul>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-w13up0000001" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I upload a file in ASP.NET Core Web API?</h3>
<div class="rank-math-answer ">

<p>Add an <code>IFormFile</code> parameter to a minimal API endpoint or controller action, send multipart/form-data, and copy the file with <code>CopyToAsync</code> to a path you build with <code>Path.GetRandomFileName</code>.</p>

</div>
</div>
<div id="faq-question-w13up0000002" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I upload multiple files with IFormFile?</h3>
<div class="rank-math-answer ">

<p>In a minimal API, bind <code>IFormFileCollection</code> and loop over it, or call <code>GetFiles</code> with a field name to get just that field&#8217;s files.</p>

</div>
</div>
<div id="faq-question-w13up0000003" class="rank-math-list-item">
<h3 class="rank-math-question ">What is the maximum file upload size in ASP.NET Core?</h3>
<div class="rank-math-answer ">

<p>Kestrel allows 30,000,000 bytes (about 28.6 MB) per request by default, and multipart bodies are capped at 128 MB. Raise them per endpoint with [RequestSizeLimit] and [RequestFormLimits].</p>

</div>
</div>
<div id="faq-question-w13up0000004" class="rank-math-list-item">
<h3 class="rank-math-question ">Why does my IFormFile minimal API endpoint return an antiforgery error?</h3>
<div class="rank-math-answer ">

<p>Since .NET 8, minimal API form binding requires antiforgery. Without the middleware you get a 500; with it but no token, a 400. Call <code>DisableAntiforgery()</code> on endpoints that use tokens, not cookies.</p>

</div>
</div>
<div id="faq-question-w13up0000005" class="rank-math-list-item">
<h3 class="rank-math-question ">Is it safe to save an uploaded file with its original file name?</h3>
<div class="rank-math-answer ">

<p>No. Treat <code>FileName</code> as display text only, save under a random name outside the app&#8217;s folder, and check the extension and file signature. Microsoft&#8217;s <a href="https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-10.0" target="_blank" rel="noopener">upload files in ASP.NET Core guide on Microsoft Learn</a> has the full security checklist.</p>

</div>
</div>
</div>
</div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>See the SQL Generated by EF Core (ToQueryString and Logging)</title>
		<link>https://aspdotnethelp.com/ef-core-see-generated-sql/</link>
		
		<dc:creator><![CDATA[Bijay Kumar]]></dc:creator>
		<pubDate>Mon, 30 Nov 2026 21:20:00 +0000</pubDate>
				<category><![CDATA[ASP.NET Core]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=3113</guid>

					<description><![CDATA[Want the short answer to EF Core how to see generated SQL? Call ToQueryString() on the query and print it: That prints the SELECT plus a DECLARE line for each parameter, and it doesn&#8217;t touch the database. To see every command your app really sends, including SaveChanges, turn on LogTo. I tested six ways on ... <a title="See the SQL Generated by EF Core (ToQueryString and Logging)" class="read-more" href="https://aspdotnethelp.com/ef-core-see-generated-sql/" aria-label="Read more about See the SQL Generated by EF Core (ToQueryString and Logging)">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Want the short answer to <strong>EF Core how to see generated SQL</strong>? Call <code>ToQueryString()</code> on the query and print it:</p>



<pre class="wp-block-code"><code>var query = db.Orders.Where(o =&gt; o.Total &gt;= minTotal);
Console.WriteLine(query.ToQueryString());</code></pre>



<p class="wp-block-paragraph">That prints the SELECT plus a DECLARE line for each parameter, and it doesn&#8217;t touch the database. To see every command your app really sends, including SaveChanges, turn on <code>LogTo</code>. I tested six ways on .NET 10, EF Core 10.0.14 and SQL Server 2025.</p>



<h2 class="wp-block-heading">Every Way to See EF Core Generated SQL</h2>



<p class="wp-block-paragraph">Each row is a section below, run against the same small orders database on <a href="https://aspdotnethelp.com/whats-new-in-dotnet-10/">.NET 10</a>:</p>



<figure class="wp-block-table"><table><thead><tr><th>Method</th><th>Shows</th><th>Best for</th></tr></thead><tbody><tr><td><code>ToQueryString()</code></td><td>SQL for one query, without running it</td><td>Quick checks while you write LINQ</td></tr><tr><td><code>LogTo(Console.WriteLine, ...)</code></td><td>Every command EF Core executes</td><td>Console apps and local debugging</td></tr><tr><td><code>EnableSensitiveDataLogging()</code></td><td>Parameter values in the log</td><td>Development only</td></tr><tr><td><code>TagWith()</code> / <code>TagWithCallSite()</code></td><td>A comment at the top of the SQL</td><td>Finding a query in logs and SQL Server</td></tr><tr><td><code>DbCommandInterceptor</code></td><td>The DbCommand itself, plus timing</td><td>Custom slow-query logging</td></tr><tr><td>appsettings.json log level</td><td>Commands through ILogger</td><td>ASP.NET Core apps</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">The Sample Project: EF Core 10 and SQL Server</h2>



<p class="wp-block-paragraph">If you&#8217;re new to DbContext and migrations, start with my <a href="https://aspdotnethelp.com/ef-core-tutorial/">EF Core tutorial for beginners</a>; this post assumes you have a context that works. My demo is one Web SDK project, so the console demos and the ASP.NET Core one share the same model:</p>



<pre class="wp-block-code"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.SqlServer&quot; Version=&quot;10.0.14&quot; /&gt;
    &lt;PackageReference Include=&quot;System.Security.Cryptography.Pkcs&quot; Version=&quot;10.0.14&quot; /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;</code></pre>



<p class="wp-block-paragraph">The Pkcs reference clears an <code>NU1903</code> warning about the older System.Security.Cryptography.Pkcs that the SQL Server provider pulls in.</p>



<p class="wp-block-paragraph">The model is two tables: customers in four US cities, and their 2026 orders in USD, with a <a href="https://aspdotnethelp.com/datetime-vs-datetimeoffset-vs-dateonly/">DateOnly</a> order date:</p>



<pre class="wp-block-code"><code>namespace W12EfSql;

public class Customer
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public required string City { get; set; }
    public required string State { get; set; }
    public List&lt;Order&gt; Orders { get; } = [];
}

public class Order
{
    public int Id { get; set; }
    public DateOnly OrderDate { get; set; }
    public decimal Total { get; set; }
    public int CustomerId { get; set; }
    public Customer Customer { get; set; } = null!;
}</code></pre>



<p class="wp-block-paragraph">The context takes its options through a <a href="https://aspdotnethelp.com/primary-constructors-in-csharp/">primary constructor</a>, so each demo can add its own logging. <code>Create()</code> is a small helper for the console demos:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public class ShopDb(DbContextOptions&lt;ShopDb&gt; options) : DbContext(options)
{
    public const string ConnectionString =
        &quot;Server=.;Database=w12_efsql;Trusted_Connection=True;TrustServerCertificate=True&quot;;

    public DbSet&lt;Customer&gt; Customers =&gt; Set&lt;Customer&gt;();
    public DbSet&lt;Order&gt; Orders =&gt; Set&lt;Order&gt;();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&lt;Customer&gt;().Property(c =&gt; c.State).HasMaxLength(2);
        modelBuilder.Entity&lt;Order&gt;().Property(o =&gt; o.Total).HasPrecision(10, 2);
    }

    // console demos: one context with whatever extra options the demo needs
    public static ShopDb Create(Action&lt;DbContextOptionsBuilder&lt;ShopDb&gt;&gt;? configure = null)
    {
        var builder = new DbContextOptionsBuilder&lt;ShopDb&gt;().UseSqlServer(ConnectionString);
        configure?.Invoke(builder);
        return new ShopDb(builder.Options);
    }
}</code></pre>



<p class="wp-block-paragraph"><code>Program.cs</code> runs one demo per argument, and <code>Seed.cs</code> rebuilds the database with five orders:</p>



<pre class="wp-block-code"><code>using System.Globalization;
using W12EfSql;

CultureInfo.CurrentCulture = new CultureInfo(&quot;en-US&quot;);   // log timestamps in US format

switch (args.FirstOrDefault())
{
    case &quot;seed&quot;: await Seed.RunAsync(); break;
    case &quot;tostring&quot;: QueryStringDemo.Run(); break;
    case &quot;terminal&quot;: await TerminalDemo.RunAsync(); break;
    case &quot;logto&quot;: await LogToDemo.RunAsync(); break;
    case &quot;sensitive&quot;: await SensitiveDemo.RunAsync(); break;
    case &quot;save&quot;: await SaveDemo.RunAsync(); break;
    case &quot;tags&quot;: await TagsDemo.RunAsync(); break;
    case &quot;intercept&quot;: await InterceptDemo.RunAsync(); break;
    case &quot;web&quot;: await WebDemo.RunAsync(); break;
    default: Console.WriteLine(&quot;Pass a demo name, for example: dotnet run -- logto&quot;); break;
}</code></pre>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public static class Seed
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create();
        db.Database.SetCommandTimeout(TimeSpan.FromMinutes(3));   // CREATE DATABASE can be slow
        await db.Database.EnsureDeletedAsync();
        await db.Database.EnsureCreatedAsync();

        var jenna = new Customer { Name = &quot;Jenna Morales&quot;, City = &quot;Austin&quot;, State = &quot;TX&quot; };
        jenna.Orders.Add(new Order { OrderDate = new(2026, 10, 3), Total = 489.99m });
        jenna.Orders.Add(new Order { OrderDate = new(2026, 10, 21), Total = 129.50m });
        var tyler = new Customer { Name = &quot;Tyler Brooks&quot;, City = &quot;Denver&quot;, State = &quot;CO&quot; };
        tyler.Orders.Add(new Order { OrderDate = new(2026, 10, 9), Total = 312.00m });
        var hannah = new Customer { Name = &quot;Hannah Price&quot;, City = &quot;Columbus&quot;, State = &quot;OH&quot; };
        hannah.Orders.Add(new Order { OrderDate = new(2026, 10, 14), Total = 74.25m });
        var marcus = new Customer { Name = &quot;Marcus Reed&quot;, City = &quot;Houston&quot;, State = &quot;TX&quot; };
        marcus.Orders.Add(new Order { OrderDate = new(2026, 11, 2), Total = 268.40m });

        db.Customers.AddRange(jenna, tyler, hannah, marcus);
        Console.WriteLine($&quot;Seeded {await db.SaveChangesAsync()} rows into w12_efsql&quot;);
    }
}</code></pre>



<p class="wp-block-paragraph">Run <code>dotnet run -- seed</code> once. It printed <code>Seeded 9 rows into w12_efsql</code>: four customers plus five orders. <code>EnsureCreatedAsync</code> keeps the demo short; a real app should create its schema with <a href="https://aspdotnethelp.com/ef-core-migrations/">EF Core migrations</a>.</p>



<h2 class="wp-block-heading">ToQueryString: Get the SQL Query for a LINQ Query</h2>



<p class="wp-block-paragraph"><code>ToQueryString()</code> works on any <code>IQueryable</code> that EF Core can translate. This one filters by a minimum total and a list of states, then projects three columns, the kind of <a href="https://aspdotnethelp.com/linq-in-csharp/">LINQ query</a> you&#8217;d write for a report:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public static class QueryStringDemo
{
    public static void Run()
    {
        using var db = ShopDb.Create();
        decimal minTotal = 250m;
        string[] states = [&quot;TX&quot;, &quot;CO&quot;];

        var query = db.Orders
            .Where(o =&gt; o.Total &gt;= minTotal &amp;&amp; states.Contains(o.Customer.State))
            .OrderByDescending(o =&gt; o.Total)
            .Select(o =&gt; new { o.Id, o.Customer.Name, o.Total });

        Console.WriteLine(query.ToQueryString());
    }
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1592" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-toquerystring-declare-parameters-generated-sql.png" alt="EF Core ToQueryString in VS Code: QueryStringDemo.cs filters orders by total and state, and the terminal prints the generated SQL with DECLARE lines for @minTotal, @states1 and @states2" class="wp-image-3155" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-toquerystring-declare-parameters-generated-sql.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-toquerystring-declare-parameters-generated-sql-261x300.png 261w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-toquerystring-declare-parameters-generated-sql-890x1024.png 890w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-toquerystring-declare-parameters-generated-sql-768x883.png 768w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-toquerystring-declare-parameters-generated-sql-1335x1536.png 1335w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">ToQueryString prints the SELECT and a DECLARE line per parameter</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>DECLARE @minTotal decimal(10,2) = 250.0;
DECLARE @states1 nvarchar(2) = N&#x27;TX&#x27;;
DECLARE @states2 nvarchar(2) = N&#x27;CO&#x27;;

SELECT [o].[Id], [c].[Name], [o].[Total]
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [o].[Total] &gt;= @minTotal AND [c].[State] IN (@states1, @states2)
ORDER BY [o].[Total] DESC</code></pre>



<p class="wp-block-paragraph">The local variable <code>minTotal</code> became the parameter <code>@minTotal</code>, and the DECLARE lines carry the real values, so you can paste the whole thing into SSMS and run it. It&#8217;s also handy in an <a href="https://aspdotnethelp.com/xunit-unit-testing-csharp/">xUnit test</a> that asserts a query keeps its WHERE clause.</p>



<p class="wp-block-paragraph">Notice the names, too. EF Core 10 simplified them (older versions printed <code>@__minTotal_0</code>), and <code>states.Contains()</code> now becomes one parameter per value, <code>@states1</code> and <code>@states2</code>. EF Core 8 and 9 sent the list as a single JSON parameter with <code>OPENJSON</code>.</p>



<h2 class="wp-block-heading">Why Doesn&#8217;t ToQueryString Show the SQL for First or Count?</h2>



<p class="wp-block-paragraph">Because <code>First()</code>, <code>Count()</code> and <code>Sum()</code> run the query right away and return a value, not an <code>IQueryable</code>. <code>db.Orders.Count()</code> is an <code>int</code>, so there&#8217;s nothing to call <code>ToQueryString()</code> on.</p>



<p class="wp-block-paragraph">The catch is that these operators change the SQL. To prove it, I printed <code>ToQueryString()</code> for a Texas filter, then ran <code>FirstAsync</code> and <code>CountAsync</code> on the same query with logging on:</p>



<p class="wp-block-paragraph">The square brackets around the category name are a <a href="https://aspdotnethelp.com/collection-expressions-in-csharp/">collection expression</a>; that overload of <code>LogTo</code> logs only the categories you list, here just the SQL commands.</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace W12EfSql;

public static class TerminalDemo
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create(o =&gt; o.LogTo(Console.WriteLine,
            [DbLoggerCategory.Database.Command.Name], LogLevel.Information,
            DbContextLoggerOptions.None));
        var texas = db.Orders.Where(o =&gt; o.Customer.State == &quot;TX&quot;);

        Console.WriteLine(&quot;ToQueryString:\n&quot; + texas.ToQueryString() + &quot;\n&quot;);
        var first = await texas.OrderBy(o =&gt; o.OrderDate).FirstAsync();
        int count = await texas.CountAsync();
        Console.WriteLine($&quot;\nFirst: {first.Total:C}, Count: {count}&quot;);
    }
}</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>ToQueryString:
SELECT [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [c].[State] = N&#x27;TX&#x27;

Executed DbCommand (62ms) [Parameters=[], CommandType=&#x27;Text&#x27;, CommandTimeout=&#x27;30&#x27;]
SELECT TOP(1) [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [c].[State] = N&#x27;TX&#x27;
ORDER BY [o].[OrderDate]
Executed DbCommand (10ms) [Parameters=[], CommandType=&#x27;Text&#x27;, CommandTimeout=&#x27;30&#x27;]
SELECT COUNT(*)
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [c].[State] = N&#x27;TX&#x27;

First: $489.99, Count: 3</code></pre>



<p class="wp-block-paragraph">The <code>ToQueryString</code> SQL has no <code>TOP(1)</code> and no <code>ORDER BY</code>, while the logged <code>FirstAsync</code> query has both, and <code>CountAsync</code> became <code>SELECT COUNT(*)</code>. Only two <code>Executed DbCommand</code> entries appear, so <code>ToQueryString()</code> itself never hit SQL Server.</p>



<p class="wp-block-paragraph">The literal <code>"TX"</code> in the lambda stayed a constant, <code>N'TX'</code>, while a variable becomes a parameter. The run returned <code>$489.99</code> for the first order and <code>3</code> Texas orders. <code>SaveChanges</code> has the same limit: it isn&#8217;t a query, so only logging shows its SQL.</p>



<h2 class="wp-block-heading">Log the Generated SQL with LogTo (Simple Logging)</h2>



<p class="wp-block-paragraph">Simple logging needs no extra package. The one-liner is <code>optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information)</code>; without a level, EF Core logs everything at Debug and up, which is a lot. I also passed <code>DbContextLoggerOptions</code> flags to drop the timestamp, which follows the current culture (see <a href="https://aspdotnethelp.com/csharp-datetime-format/">C# DateTime formats</a>):</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace W12EfSql;

public static class LogToDemo
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create(o =&gt; o.LogTo(Console.WriteLine, LogLevel.Information,
            DbContextLoggerOptions.Level | DbContextLoggerOptions.Id | DbContextLoggerOptions.Category));

        decimal minTotal = 250m;
        var bigOrders = await db.Orders
            .Where(o =&gt; o.Total &gt;= minTotal)
            .ToListAsync();

        Console.WriteLine($&quot;Orders over {minTotal:C}: {bigOrders.Count}&quot;);
    }
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1592" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-logto-console-executed-dbcommand-sql.png" alt="EF Core LogTo in VS Code: LogToDemo.cs logs to Console.WriteLine at LogLevel.Information, and the terminal shows RelationalEventId.CommandExecuted with Executed DbCommand and the SELECT" class="wp-image-3151" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-logto-console-executed-dbcommand-sql.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-logto-console-executed-dbcommand-sql-261x300.png 261w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-logto-console-executed-dbcommand-sql-890x1024.png 890w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-logto-console-executed-dbcommand-sql-768x883.png 768w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-logto-console-executed-dbcommand-sql-1335x1536.png 1335w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">LogTo prints one Executed DbCommand entry per SQL statement</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>info: RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command) 
      Executed DbCommand (52ms) [Parameters=[@minTotal=&#x27;?&#x27; (Precision = 10) (Scale = 2) (DbType = Decimal)], CommandType=&#x27;Text&#x27;, CommandTimeout=&#x27;30&#x27;]
      SELECT [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
      FROM [Orders] AS [o]
      WHERE [o].[Total] &gt;= @minTotal
Orders over $250.00: 3</code></pre>



<p class="wp-block-paragraph">Each entry starts with the level, the event ID (<code>RelationalEventId.CommandExecuted[20101]</code>) and the category, then the duration, the parameters and the SQL. The query found 3 orders of $250 or more.</p>



<p class="wp-block-paragraph"><strong>Note:</strong> the <code>'?'</code> isn&#8217;t a bug. EF Core hides parameter values by default; the sensitive data section below turns them on.</p>



<h2 class="wp-block-heading">Show Parameter Values with EnableSensitiveDataLogging</h2>



<p class="wp-block-paragraph"><code>EnableSensitiveDataLogging()</code> puts the real parameter values in the log. <code>EnableDetailedErrors()</code> is its usual partner: it wraps each column read in a <a href="https://aspdotnethelp.com/try-catch-in-csharp/">try-catch</a> so a NULL-in-a-required-column error names the property:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace W12EfSql;

public static class SensitiveDemo
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create(o =&gt; o
            .LogTo(Console.WriteLine, [DbLoggerCategory.Database.Command.Name], LogLevel.Information,
                DbContextLoggerOptions.None)
            .EnableSensitiveDataLogging()     // development only: logs parameter values
            .EnableDetailedErrors());

        decimal minTotal = 250m;
        var bigOrders = await db.Orders
            .Where(o =&gt; o.Total &gt;= minTotal)
            .ToListAsync();

        Console.WriteLine($&quot;Orders over {minTotal:C}: {bigOrders.Count}&quot;);
    }
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1592" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-enablesensitivedatalogging-parameter-values-log.png" alt="EF Core EnableSensitiveDataLogging in VS Code: SensitiveDemo.cs adds EnableSensitiveDataLogging and EnableDetailedErrors, and the log shows the real @minTotal parameter value instead of a question mark" class="wp-image-3150" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-enablesensitivedatalogging-parameter-values-log.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-enablesensitivedatalogging-parameter-values-log-261x300.png 261w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-enablesensitivedatalogging-parameter-values-log-890x1024.png 890w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-enablesensitivedatalogging-parameter-values-log-768x883.png 768w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-enablesensitivedatalogging-parameter-values-log-1335x1536.png 1335w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">With sensitive data logging on, the parameter value shows up in the log</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>Executed DbCommand (52ms) [Parameters=[@minTotal=&#x27;250&#x27; (Precision = 10) (Scale = 2)], CommandType=&#x27;Text&#x27;, CommandTimeout=&#x27;30&#x27;]
SELECT [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
FROM [Orders] AS [o]
WHERE [o].[Total] &gt;= @minTotal
Orders over $250.00: 3</code></pre>



<p class="wp-block-paragraph">Now the log says <code>@minTotal='250'</code> instead of <code>'?'</code>. That&#8217;s exactly what you need when a query returns the wrong rows.</p>



<p class="wp-block-paragraph"><strong>Important:</strong> never ship this to production. Parameter values are customer names, emails and IDs. EF Core 10 also redacts constants it inlines into the SQL (they log as <code>?</code>), and this switch turns those back on too.</p>



<h2 class="wp-block-heading">See the SQL That SaveChanges Generates</h2>



<p class="wp-block-paragraph">Inserts, updates and deletes don&#8217;t have a query to call <code>ToQueryString()</code> on, so logging is the only way in. This demo updates one of Hannah Price&#8217;s orders and adds two new ones:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace W12EfSql;

public static class SaveDemo
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create(o =&gt; o
            .LogTo(Console.WriteLine, [DbLoggerCategory.Database.Command.Name], LogLevel.Information,
                DbContextLoggerOptions.None)
            .EnableSensitiveDataLogging());

        var hannah = await db.Customers.Include(c =&gt; c.Orders).SingleAsync(c =&gt; c.Name == &quot;Hannah Price&quot;);
        hannah.Orders[0].Total = 79.25m;                                   // UPDATE
        hannah.Orders.Add(new Order { OrderDate = new(2026, 11, 5), Total = 58.00m });   // INSERT
        hannah.Orders.Add(new Order { OrderDate = new(2026, 11, 6), Total = 112.75m });  // INSERT

        Console.WriteLine($&quot;Saved {await db.SaveChangesAsync()} rows&quot;);
    }
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1592" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-savechanges-generated-sql-insert-update-output.png" alt="EF Core SaveChanges SQL in VS Code: SaveDemo.cs updates one order and adds two, and the log shows one batch with UPDATE Orders OUTPUT 1 and MERGE Orders with OUTPUT INSERTED.Id" class="wp-image-3152" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-savechanges-generated-sql-insert-update-output.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-savechanges-generated-sql-insert-update-output-261x300.png 261w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-savechanges-generated-sql-insert-update-output-890x1024.png 890w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-savechanges-generated-sql-insert-update-output-768x883.png 768w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-savechanges-generated-sql-insert-update-output-1335x1536.png 1335w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">One SaveChangesAsync call sent the UPDATE and both INSERTs in a single batch</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>Executed DbCommand (68ms) [Parameters=[], CommandType=&#x27;Text&#x27;, CommandTimeout=&#x27;30&#x27;]
SELECT [c0].[Id], [c0].[City], [c0].[Name], [c0].[State], [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
FROM (
    SELECT TOP(2) [c].[Id], [c].[City], [c].[Name], [c].[State]
    FROM [Customers] AS [c]
    WHERE [c].[Name] = N&#x27;Hannah Price&#x27;
) AS [c0]
LEFT JOIN [Orders] AS [o] ON [c0].[Id] = [o].[CustomerId]
ORDER BY [c0].[Id]
Executed DbCommand (42ms) [Parameters=[@p1=&#x27;4&#x27;, @p0=&#x27;79.25&#x27; (Precision = 10) (Scale = 2), @p2=&#x27;3&#x27;, @p3=&#x27;11/05/2026&#x27; (DbType = Date), @p4=&#x27;58.00&#x27; (Precision = 10) (Scale = 2), @p5=&#x27;3&#x27;, @p6=&#x27;11/06/2026&#x27; (DbType = Date), @p7=&#x27;112.75&#x27; (Precision = 10) (Scale = 2)], CommandType=&#x27;Text&#x27;, CommandTimeout=&#x27;30&#x27;]
SET NOCOUNT ON;
UPDATE [Orders] SET [Total] = @p0
OUTPUT 1
WHERE [Id] = @p1;
MERGE [Orders] USING (
VALUES (@p2, @p3, @p4, 0),
(@p5, @p6, @p7, 1)) AS i ([CustomerId], [OrderDate], [Total], _Position) ON 1=0
WHEN NOT MATCHED THEN
INSERT ([CustomerId], [OrderDate], [Total])
VALUES (i.[CustomerId], i.[OrderDate], i.[Total])
OUTPUT INSERTED.[Id], i._Position;
Saved 3 rows</code></pre>



<p class="wp-block-paragraph">The first command is the <code>Include</code> load. The second is the whole save in one round trip: an UPDATE for the changed total, then a <code>MERGE</code> that inserts both orders and returns their new keys with <code>OUTPUT INSERTED.[Id]</code>. <code>SaveChangesAsync</code> reported 3 rows.</p>



<p class="wp-block-paragraph">EF Core uses <code>MERGE</code> here so it can match each generated Id back to the right object through <code>_Position</code>. For the endpoint side of saving data, see my <a href="https://aspdotnethelp.com/aspnet-core-web-api-crud-ef-core/">ASP.NET Core Web API CRUD with EF Core</a> post.</p>



<h2 class="wp-block-heading">Tag EF Core Queries with TagWith and TagWithCallSite</h2>



<p class="wp-block-paragraph">In a busy log, every SELECT looks the same. <code>TagWith()</code> adds your own comment to the SQL, and <code>TagWithCallSite()</code> adds the file name and line number where the query was written:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public static class TagsDemo
{
    public static async Task RunAsync()
    {
        using var db = ShopDb.Create();
        decimal minTotal = 250m;

        var query = db.Orders
            .TagWith(&quot;Sales dashboard: Texas orders over $250&quot;)
            .TagWithCallSite()
            .Where(o =&gt; o.Customer.State == &quot;TX&quot; &amp;&amp; o.Total &gt;= minTotal);

        Console.WriteLine(query.ToQueryString());
        Console.WriteLine($&quot;\nRows: {(await query.ToListAsync()).Count}&quot;);
    }
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1592" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-tagwith-query-tag-comment-in-sql.png" alt="EF Core TagWith and TagWithCallSite in VS Code: TagsDemo.cs tags a Texas orders query, and ToQueryString shows the SQL comment lines Sales dashboard and File TagsDemo.cs line number" class="wp-image-3154" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-tagwith-query-tag-comment-in-sql.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-tagwith-query-tag-comment-in-sql-261x300.png 261w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-tagwith-query-tag-comment-in-sql-890x1024.png 890w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-tagwith-query-tag-comment-in-sql-768x883.png 768w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-tagwith-query-tag-comment-in-sql-1335x1536.png 1335w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">Query tags become SQL comments at the top of the command</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>DECLARE @minTotal decimal(10,2) = 250.0;

-- Sales dashboard: Texas orders over $250
-- File: C:\DotNetDemo\W12EfSql\TagsDemo.cs:14

SELECT [o].[Id], [o].[CustomerId], [o].[OrderDate], [o].[Total]
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [c].[State] = N&#x27;TX&#x27; AND [o].[Total] &gt;= @minTotal

Rows: 2</code></pre>



<p class="wp-block-paragraph">Both tags became <code>--</code> comments above the SELECT, and they travel with the command, so they show up in the log, in <code>ToQueryString()</code> and on SQL Server. The query returned 2 rows.</p>



<p class="wp-block-paragraph">Tags are always literal strings in the SQL, so don&#8217;t put values that change per call in them.</p>



<h2 class="wp-block-heading">Find an EF Core Query in SQL Server</h2>



<p class="wp-block-paragraph">Sometimes the app isn&#8217;t yours to change. SQL Server keeps statistics for cached plans, and the tag makes our query easy to find. After the tags demo ran, I asked <code>sys.dm_exec_query_stats</code>:</p>



<pre class="wp-block-code"><code>sqlcmd -S . -E -d w12_efsql -W -Q &quot;SET NOCOUNT ON; SELECT qs.execution_count, LEFT(REPLACE(REPLACE(st.text, CHAR(13), &#x27;&#x27;), CHAR(10), &#x27; &#x27;), 70) AS sql_text FROM sys.dm_exec_query_stats AS qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st WHERE st.text LIKE &#x27;%Sales dashboard%&#x27; AND st.text NOT LIKE &#x27;%dm_exec%&#x27;&quot;</code></pre>



<pre class="wp-block-code"><code>execution_count sql_text
--------------- --------
1 (@minTotal decimal(10,2))-- Sales dashboard: Texas orders over $250 --</code></pre>



<p class="wp-block-paragraph">The text starts with <code>(@minTotal decimal(10,2))</code> because EF Core sends parameterized SQL through <code>sp_executesql</code>, and <code>execution_count</code> tells you how many times that cached plan ran. You need the <code>VIEW SERVER STATE</code> permission to read these views.</p>



<p class="wp-block-paragraph">For a live trace, use an Extended Events session on the sql_batch_completed and rpc_completed events (SSMS has an XEvent Profiler node for this). SQL Server Profiler still opens, but Microsoft lists SQL Trace and Profiler as deprecated.</p>



<h2 class="wp-block-heading">Log SQL with a DbCommandInterceptor</h2>



<p class="wp-block-paragraph">An interceptor sees the actual <code>DbCommand</code> before or after it runs. For plain logging, Microsoft says <code>LogTo</code> is the better fit, but an interceptor is handy for your own format, timing or a slow-query alert. <code>ReaderExecutedAsync</code> runs after each <a href="https://aspdotnethelp.com/async-await-in-csharp/">awaited</a> query:</p>



<pre class="wp-block-code"><code>using System.Data.Common;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace W12EfSql;

public class SqlTimingInterceptor : DbCommandInterceptor
{
    public override ValueTask&lt;DbDataReader&gt; ReaderExecutedAsync(DbCommand command,
        CommandExecutedEventData eventData, DbDataReader result, CancellationToken cancellationToken = default)
    {
        string firstLine = command.CommandText.Split(&#x27;\n&#x27;)[0].Trim();
        Console.WriteLine($&quot;[SQL {eventData.Duration.TotalMilliseconds:F0} ms] {firstLine} ...&quot;);
        return base.ReaderExecutedAsync(command, eventData, result, cancellationToken);
    }
}</code></pre>



<p class="wp-block-paragraph">The interceptor holds no state, so one instance can serve every context. Pass the <a href="https://aspdotnethelp.com/cancellationtoken-in-csharp/">CancellationToken</a> through to the base call, then register it with <code>AddInterceptors</code>:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public static class InterceptDemo
{
    static readonly SqlTimingInterceptor Timing = new();   // stateless: one instance for every context

    public static async Task RunAsync()
    {
        using var db = ShopDb.Create(o =&gt; o.AddInterceptors(Timing));

        var customers = await db.Customers.OrderBy(c =&gt; c.Name).ToListAsync();
        var total = await db.Orders.SumAsync(o =&gt; o.Total);
        Console.WriteLine($&quot;{customers.Count} customers, {total:C} in orders&quot;);
    }
}</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>[SQL 61 ms] SELECT [c].[Id], [c].[City], [c].[Name], [c].[State] ...
[SQL 8 ms] SELECT COALESCE(SUM([o].[Total]), 0.0) ...
4 customers, $1,449.89 in orders</code></pre>



<p class="wp-block-paragraph">Each query printed its time and first SQL line (4 customers, $1,449.89 in orders); times vary from run to run. To flag slow queries, compare <code>eventData.Duration</code> with a threshold.</p>



<h2 class="wp-block-heading">How Do You Log EF Core SQL in ASP.NET Core?</h2>



<p class="wp-block-paragraph">In ASP.NET Core you don&#8217;t need <code>LogTo</code>. <code>AddDbContext</code> registers a <a href="https://aspdotnethelp.com/dependency-injection-lifetimes-aspnet-core/">scoped</a> context and hands EF Core the app&#8217;s logger factory, so the SQL is controlled by the <code>Logging:LogLevel</code> section in <code>appsettings.json</code>:</p>



<pre class="wp-block-code"><code>{
  &quot;Urls&quot;: &quot;http://localhost:5904&quot;,
  &quot;Logging&quot;: {
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Warning&quot;,
      &quot;Microsoft.EntityFrameworkCore.Database.Command&quot;: &quot;Information&quot;
    }
  }
}</code></pre>



<p class="wp-block-paragraph"><code>Default</code> is Warning to keep the demo quiet, and the more specific <code>Microsoft.EntityFrameworkCore.Database.Command</code> category wins for SQL. The <a href="https://aspdotnethelp.com/minimal-api-vs-controllers-aspnet-core/">minimal API</a> below starts on port 5904, calls itself once with <a href="https://aspdotnethelp.com/httpclient-in-csharp/">HttpClient</a> and stops:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;

namespace W12EfSql;

public static class WebDemo
{
    public static async Task RunAsync()
    {
        var builder = WebApplication.CreateBuilder();
        builder.Services.AddDbContext&lt;ShopDb&gt;(o =&gt; o.UseSqlServer(ShopDb.ConnectionString));
        var app = builder.Build();

        app.MapGet(&quot;/orders/{state}&quot;, (string state, ShopDb db) =&gt;
            db.Orders.Where(o =&gt; o.Customer.State == state).Select(o =&gt; o.Total).ToListAsync());

        await app.StartAsync();
        using var http = new HttpClient();
        Console.WriteLine(await http.GetStringAsync(&quot;http://localhost:5904/orders/TX&quot;));
        await app.StopAsync();
    }
}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1592" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-appsettings-ef-core-database-command-logging.png" alt="ASP.NET Core EF Core SQL logging in VS Code: WebDemo.cs registers AddDbContext with a minimal API, and the console logger prints Microsoft.EntityFrameworkCore.Database.Command Executed DbCommand from appsettings.json" class="wp-image-3149" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-appsettings-ef-core-database-command-logging.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-appsettings-ef-core-database-command-logging-261x300.png 261w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-appsettings-ef-core-database-command-logging-890x1024.png 890w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-appsettings-ef-core-database-command-logging-768x883.png 768w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-appsettings-ef-core-database-command-logging-1335x1536.png 1335w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">appsettings.json turned on the Database.Command category; no LogTo in the code</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (48ms) [Parameters=[@state=&#x27;?&#x27; (Size = 2)], CommandType=&#x27;Text&#x27;, CommandTimeout=&#x27;30&#x27;]
      SELECT [o].[Total]
      FROM [Orders] AS [o]
      INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
      WHERE [c].[State] = @state
[489.99,129.50,268.40]</code></pre>



<p class="wp-block-paragraph">The console logger shows the category name, <code>Microsoft.EntityFrameworkCore.Database.Command[20101]</code>, and the endpoint returned <code>[489.99,129.50,268.40]</code>, the three Texas totals. My post on <a href="https://aspdotnethelp.com/logging-in-aspnet-core/">logging in ASP.NET Core</a> covers levels, filters and file logging with Serilog.</p>



<p class="wp-block-paragraph">In a real app, set that category to Information in <code>appsettings.Development.json</code> only, as in my guide to <a href="https://aspdotnethelp.com/appsettings-per-environment-aspnet-core/">appsettings per environment</a>, and call <code>EnableSensitiveDataLogging()</code> only when <code>builder.Environment.IsDevelopment()</code> is true.</p>



<p class="wp-block-paragraph">If you&#8217;re tuning a data layer, these are worth a look next:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/asp-net-core-tutorials/">ASP.NET Core tutorials, from minimal APIs to auth</a></li>

<li><a href="https://aspdotnethelp.com/dotnet-versions/">Every .NET version and its support dates</a></li>

<li><a href="https://aspdotnethelp.com/csharp-tutorials/">C# tutorials by topic</a></li>

<li><a href="https://aspdotnethelp.com/learn-csharp/">The C# learning path</a></li>
</ul>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-efq120000001" class="rank-math-list-item">
<h3 class="rank-math-question ">Does ToQueryString run the query against the database?</h3>
<div class="rank-math-answer ">

<p>No. It only translates the LINQ to SQL. With logging on, my run showed no <code>Executed DbCommand</code> entry for the <code>ToQueryString()</code> call, only for the queries I actually executed.</p>

</div>
</div>
<div id="faq-question-efq120000002" class="rank-math-list-item">
<h3 class="rank-math-question ">Why does the EF Core log show a question mark instead of my parameter value?</h3>
<div class="rank-math-answer ">

<p>EF Core hides parameter values by default because they can be personal data. Add <code>EnableSensitiveDataLogging()</code> in development to log them.</p>

</div>
</div>
<div id="faq-question-efq120000003" class="rank-math-list-item">
<h3 class="rank-math-question ">Is it safe to keep EF Core SQL logging on in production?</h3>
<div class="rank-math-answer ">

<p>Logging commands at Information level is safe but noisy, so most apps keep it at Warning and raise it while troubleshooting. Keep sensitive data logging off. See <a href="https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/simple-logging" target="_blank" rel="noopener">EF Core simple logging on Microsoft Learn</a> for every filter option.</p>

</div>
</div>
<div id="faq-question-efq120000004" class="rank-math-list-item">
<h3 class="rank-math-question ">Can I write the generated SQL to a file?</h3>
<div class="rank-math-answer ">

<p>Yes. Pass a <code>StreamWriter</code>&#8216;s <code>WriteLine</code> to <code>LogTo</code> and dispose the writer with the context, or in ASP.NET Core use a logging provider that writes files.</p>

</div>
</div>
<div id="faq-question-efq120000005" class="rank-math-list-item">
<h3 class="rank-math-question ">Where can I see the SQL in the Visual Studio debugger?</h3>
<div class="rank-math-answer ">

<p>Hover over the query variable and open its <code>DebugView</code>; the <code>Query</code> entry shows the same SQL as <code>ToQueryString()</code>.</p>

</div>
</div>
</div>
</div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>StateHasChanged in Blazor: Why Your Component Is Not Refreshing</title>
		<link>https://aspdotnethelp.com/blazor-statehaschanged/</link>
		
		<dc:creator><![CDATA[Bijay Kumar]]></dc:creator>
		<pubDate>Mon, 30 Nov 2026 15:15:00 +0000</pubDate>
				<category><![CDATA[Blazor]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=3112</guid>

					<description><![CDATA[My first live-orders page in Blazor used a timer to add an online order every second. The console counted up, but the page never refreshed. Adding StateHasChanged() to the timer then crashed the whole app. That&#8217;s the classic Blazor StateHasChanged not refreshing trap: Blazor re-renders on its own only after its own events and lifecycle ... <a title="StateHasChanged in Blazor: Why Your Component Is Not Refreshing" class="read-more" href="https://aspdotnethelp.com/blazor-statehaschanged/" aria-label="Read more about StateHasChanged in Blazor: Why Your Component Is Not Refreshing">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">My first live-orders page in Blazor used a timer to add an online order every second. The console counted up, but the page never refreshed. Adding StateHasChanged() to the timer then crashed the whole app.</p>



<p class="wp-block-paragraph">That&#8217;s the classic <strong>Blazor StateHasChanged not refreshing</strong> trap: Blazor re-renders on its own only after its own events and lifecycle methods.</p>



<p class="wp-block-paragraph"><strong>Quick answer:</strong> call <code>StateHasChanged()</code> for changes Blazor can&#8217;t see, wrapped in <code>InvokeAsync</code> when the code runs off Blazor&#8217;s thread. Below are seven real cases on .NET 10.</p>



<h2 class="wp-block-heading">When Does Blazor Re-render a Component Automatically?</h2>



<p class="wp-block-paragraph">A component that inherits <code>ComponentBase</code> re-renders on its own only in the cases on the left (per Microsoft Learn), the same points you see in the <a href="https://aspdotnethelp.com/blazor-component-lifecycle/">Blazor component lifecycle</a>:</p>



<figure class="wp-block-table"><table><thead><tr><th>Re-renders automatically</th><th>Needs StateHasChanged()</th></tr></thead><tbody><tr><td>After one of its own event handlers (<code>@onclick</code>, <code>@bind</code>)</td><td>Timer callbacks</td></tr><tr><td>After its lifecycle methods (<code>OnInitializedAsync</code>, &#8230;)</td><td>C# events raised by a service</td></tr><tr><td>After the parent passes new parameters</td><td>A sibling or parent whose data changed</td></tr><tr><td>After a cascading value changes</td><td>Progress in the middle of an async handler</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">An <code>async Task</code> handler gets two automatic renders: when the task is first returned and when it completes.</p>



<h2 class="wp-block-heading">Set Up the StateHasChanged Demo App</h2>



<p class="wp-block-paragraph">I used the .NET 10 SDK (10.0.402) and the Blazor Web App template. If the template is new to you, my <a href="https://aspdotnethelp.com/blazor-tutorial-for-beginners/">Blazor tutorial for beginners</a> walks through it.</p>



<pre class="wp-block-code"><code>dotnet new blazor -o W12StateHas</code></pre>



<p class="wp-block-paragraph">I deleted <code>appsettings.Development.json</code> and kept the template&#8217;s <code>appsettings.json</code> and project file, plus a plain http launch profile on port 5902:</p>



<pre class="wp-block-code"><code>{
  &quot;Logging&quot;: {
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Information&quot;,
      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;
    }
  },
  &quot;AllowedHosts&quot;: &quot;*&quot;
}</code></pre>



<pre class="wp-block-code"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;BlazorDisableThrowNavigationException&gt;true&lt;/BlazorDisableThrowNavigationException&gt;
  &lt;/PropertyGroup&gt;

&lt;/Project&gt;</code></pre>



<pre class="wp-block-code"><code>{
  &quot;$schema&quot;: &quot;https://json.schemastore.org/launchsettings.json&quot;,
  &quot;profiles&quot;: {
    &quot;http&quot;: {
      &quot;commandName&quot;: &quot;Project&quot;,
      &quot;dotnetRunMessages&quot;: true,
      &quot;launchBrowser&quot;: false,
      &quot;applicationUrl&quot;: &quot;http://localhost:5902&quot;,
      &quot;environmentVariables&quot;: {
        &quot;ASPNETCORE_ENVIRONMENT&quot;: &quot;Development&quot;
      }
    }
  }
}</code></pre>



<p class="wp-block-paragraph"><code>Program.cs</code> registers a cart service as scoped (one per circuit, see <a href="https://aspdotnethelp.com/dependency-injection-lifetimes-aspnet-core/">DI lifetimes</a>) and drops the https redirect:</p>



<pre class="wp-block-code"><code>using W12StateHas.Components;
using W12StateHas.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddScoped&lt;CartState&gt;();   // one cart per circuit

builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler(&quot;/Error&quot;, createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseStatusCodePagesWithReExecute(&quot;/not-found&quot;, createScopeForStatusCodePages: true);

app.UseAntiforgery();

app.MapStaticAssets();
app.MapRazorComponents&lt;App&gt;()
    .AddInteractiveServerRenderMode();

app.Run();</code></pre>



<h2 class="wp-block-heading">Why Is My Blazor Component Not Refreshing After a Timer Tick?</h2>



<p class="wp-block-paragraph">Here&#8217;s the page that started it, <code>LiveOrders.razor</code>. A <code>System.Threading.Timer</code> adds an order every second, starting after the first interactive render:</p>



<pre class="wp-block-code"><code>
@page &quot;/live-orders&quot;
@rendermode InteractiveServer
@implements IDisposable

&lt;PageTitle&gt;Live Orders&lt;/PageTitle&gt;

&lt;h1&gt;Harbor Lane Bakery - Live Orders&lt;/h1&gt;
&lt;p class=&quot;fs-4&quot;&gt;Online orders today: &lt;strong id=&quot;count&quot;&gt;@ordersToday&lt;/strong&gt;&lt;/p&gt;

@code {
    private int ordersToday;
    private Timer? timer;

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
            timer = new Timer(_ =&gt; OnNewOrder(), null, 1000, 1000);
    }

    private void OnNewOrder()
    {
        ordersToday++;
        Console.WriteLine($&quot;Timer tick: ordersToday = {ordersToday}&quot;);
    }

    public void Dispose() =&gt; timer?.Dispose();
}
</code></pre>



<p class="wp-block-paragraph">I opened the page in Edge and waited 5.5 seconds. The server console counted every tick:</p>



<pre class="wp-block-code"><code>Timer tick: ordersToday = 1
Timer tick: ordersToday = 2
Timer tick: ordersToday = 3
Timer tick: ordersToday = 4
Timer tick: ordersToday = 5</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1002" height="422" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-timer-page-not-refreshing-count-stuck-at-0.png" alt="Blazor Live Orders page in Edge still showing Online orders today: 0 while a System.Threading.Timer has already incremented the field" class="wp-image-3162" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-timer-page-not-refreshing-count-stuck-at-0.png 1002w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-timer-page-not-refreshing-count-stuck-at-0-300x126.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-timer-page-not-refreshing-count-stuck-at-0-768x323.png 768w" sizes="auto, (max-width: 1002px) 100vw, 1002px" /><figcaption class="wp-element-caption">The field changed on the server, but the page still shows 0</figcaption></figure>
</div>


<p class="wp-block-paragraph">The field kept climbing (it hit 11 before I stopped the server), but the page showed <code>0</code>. A timer isn&#8217;t a Blazor event, so nothing asked for a render.</p>



<h2 class="wp-block-heading">StateHasChanged From a Timer Throws a Dispatcher Exception</h2>



<p class="wp-block-paragraph">The obvious fix is one line at the end of <code>OnNewOrder</code>:</p>



<pre class="wp-block-code"><code>    private void OnNewOrder()
    {
        ordersToday++;
        Console.WriteLine($&quot;Timer tick: ordersToday = {ordersToday}&quot;);
        StateHasChanged();   // called from a thread-pool thread
    }</code></pre>



<p class="wp-block-paragraph">The first tick killed the app. The terminal showed this, then the server process exited:</p>



<pre class="wp-block-code"><code>Unhandled exception. System.InvalidOperationException: The current thread is not associated with the Dispatcher. Use InvokeAsync() to switch execution to the Dispatcher when triggering rendering or component state.</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1784" height="1242" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-statehaschanged-timer-dispatcher-exception.png" alt="VS Code with LiveOrders.razor open and the dotnet run terminal showing Unhandled exception System.InvalidOperationException The current thread is not associated with the Dispatcher" class="wp-image-3165" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-statehaschanged-timer-dispatcher-exception.png 1784w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-statehaschanged-timer-dispatcher-exception-300x209.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-statehaschanged-timer-dispatcher-exception-1024x713.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-statehaschanged-timer-dispatcher-exception-768x535.png 768w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-statehaschanged-timer-dispatcher-exception-1536x1069.png 1536w" sizes="auto, (max-width: 1784px) 100vw, 1784px" /><figcaption class="wp-element-caption">StateHasChanged() from the timer thread: unhandled InvalidOperationException</figcaption></figure>
</div>


<p class="wp-block-paragraph"><code>StateHasChanged</code> can only run on the renderer&#8217;s synchronization context. A <code>System.Threading.Timer</code> callback runs on a thread-pool thread, and an unhandled exception there ends the whole process, so every connected user loses the app.</p>



<h2 class="wp-block-heading">Fix It With InvokeAsync(StateHasChanged)</h2>



<p class="wp-block-paragraph"><code>InvokeAsync</code> takes a <a href="https://aspdotnethelp.com/delegates-in-csharp/">delegate</a> and runs it on Blazor&#8217;s dispatcher. I moved the field update inside it too, so it can&#8217;t race with a render:</p>



<pre class="wp-block-code"><code>    private void OnNewOrder() =&gt; _ = InvokeAsync(() =&gt;
    {
        ordersToday++;
        Console.WriteLine($&quot;Timer tick: ordersToday = {ordersToday}&quot;);
        StateHasChanged();
    });</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1002" height="422" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-invokeasync-statehaschanged-timer-count-refreshing.png" alt="Blazor Live Orders page in Edge showing the online order count going up after the timer callback calls InvokeAsync with StateHasChanged" class="wp-image-3158" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-invokeasync-statehaschanged-timer-count-refreshing.png 1002w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-invokeasync-statehaschanged-timer-count-refreshing-300x126.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-invokeasync-statehaschanged-timer-count-refreshing-768x323.png 768w" sizes="auto, (max-width: 1002px) 100vw, 1002px" /><figcaption class="wp-element-caption">With InvokeAsync, every tick shows up on the page</figcaption></figure>
</div>


<p class="wp-block-paragraph">Now the page kept up: it read <code>5</code> at 5.5 seconds and kept climbing. Keep the <code>Dispose</code> method: it stops the timer when the user leaves the page. For timers you await, a <code>PeriodicTimer</code> plus a <a href="https://aspdotnethelp.com/cancellationtoken-in-csharp/">CancellationToken</a> is the cleaner pattern.</p>



<h2 class="wp-block-heading">Refresh Another Component With a State Container Event</h2>



<p class="wp-block-paragraph">The second bug was a cart badge. A menu item adds to a shared <code>CartState</code> service, and a badge in the heading shows the count:</p>



<pre class="wp-block-code"><code>namespace W12StateHas.Services;

public class CartState
{
    private readonly List&lt;string&gt; items = [];

    public IReadOnlyList&lt;string&gt; Items =&gt; items;

    public event Action? OnChange;

    public void Add(string item)
    {
        items.Add(item);
        Console.WriteLine($&quot;CartState.Add: {item} ({items.Count} items)&quot;);
        OnChange?.Invoke();
    }
}</code></pre>



<pre class="wp-block-code"><code>
@using System.Globalization
@using W12StateHas.Services
@inject CartState Cart

&lt;div class=&quot;card mb-2&quot; style=&quot;max-width: 26rem;&quot;&gt;
    &lt;div class=&quot;card-body py-2 d-flex justify-content-between align-items-center&quot;&gt;
        &lt;span&gt;@Name - @Price.ToString(&quot;C&quot;, Us) @(added &gt; 0 ? $&quot;(added {added})&quot; : &quot;&quot;)&lt;/span&gt;
        &lt;button class=&quot;btn btn-sm btn-outline-primary&quot; data-item=&quot;@Name&quot; @onclick=&quot;Add&quot;&gt;Add&lt;/button&gt;
    &lt;/div&gt;
&lt;/div&gt;

@code {
    private static readonly CultureInfo Us = new(&quot;en-US&quot;);
    private int added;

    [Parameter] public string Name { get; set; } = &quot;&quot;;
    [Parameter] public decimal Price { get; set; }

    private void Add()
    {
        added++;
        Cart.Add(Name);
    }
}
</code></pre>



<pre class="wp-block-code"><code>
@page &quot;/menu&quot;
@rendermode InteractiveServer

&lt;PageTitle&gt;Menu&lt;/PageTitle&gt;

&lt;h1&gt;Harbor Lane Bakery &lt;CartBadge /&gt;&lt;/h1&gt;

&lt;MenuItem Name=&quot;Blueberry muffin&quot; Price=&quot;3.75m&quot; /&gt;
&lt;MenuItem Name=&quot;Maple scone&quot; Price=&quot;4.25m&quot; /&gt;
&lt;MenuItem Name=&quot;Sourdough loaf&quot; Price=&quot;8.50m&quot; /&gt;
</code></pre>



<p class="wp-block-paragraph">The first <code>CartBadge.razor</code> just read the count:</p>



<pre class="wp-block-code"><code>
@using W12StateHas.Services
@inject CartState Cart

&lt;span class=&quot;badge bg-primary fs-6 ms-2&quot;&gt;Cart: @Cart.Items.Count&lt;/span&gt;
</code></pre>



<p class="wp-block-paragraph">I clicked Add on the muffin and the scone. Each item showed &#8220;(added 1)&#8221;, the console logged 2 items, and the badge stayed at 0. The click re-rendered only the <code>MenuItem</code> that received it; the badge isn&#8217;t its child.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1012" height="304" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-state-container-cart-badge-before-after.png" alt="Before and after in Edge: the Blazor cart badge stays at Cart: 0 after two Add clicks, then shows Cart: 2 once CartBadge subscribes to the OnChange event" class="wp-image-3159" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-state-container-cart-badge-before-after.png 1012w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-state-container-cart-badge-before-after-300x90.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-state-container-cart-badge-before-after-768x231.png 768w" sizes="auto, (max-width: 1012px) 100vw, 1012px" /><figcaption class="wp-element-caption">Left: the badge doesn&#8217;t refresh. Right: the badge subscribed to CartState.OnChange</figcaption></figure>
</div>


<p class="wp-block-paragraph">The fix is to subscribe to the service&#8217;s <a href="https://aspdotnethelp.com/events-in-csharp/">C# event</a> and unsubscribe in <code>Dispose</code>:</p>



<pre class="wp-block-code"><code>
@using W12StateHas.Services
@implements IDisposable
@inject CartState Cart

&lt;span class=&quot;badge bg-primary fs-6 ms-2&quot;&gt;Cart: @Cart.Items.Count&lt;/span&gt;

@code {
    protected override void OnInitialized() =&gt; Cart.OnChange += Refresh;

    private void Refresh() =&gt; _ = InvokeAsync(StateHasChanged);

    public void Dispose()
    {
        Cart.OnChange -= Refresh;
        Console.WriteLine($&quot;CartBadge.Dispose ({RendererInfo.Name}): unsubscribed&quot;);
    }
}
</code></pre>



<p class="wp-block-paragraph">This time I added both items and then clicked the W12StateHas home link:</p>



<pre class="wp-block-code"><code>CartBadge.Dispose (Static): unsubscribed
CartState.Add: Blueberry muffin (1 items)
CartState.Add: Maple scone (2 items)
CartBadge.Dispose (Server): unsubscribed</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1184" height="1392" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-state-container-onchange-dispose-unsubscribe.png" alt="VS Code with CartBadge.razor open and the terminal showing CartState.Add for two items and CartBadge.Dispose unsubscribed when the user leaves the menu page" class="wp-image-3163" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-state-container-onchange-dispose-unsubscribe.png 1184w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-state-container-onchange-dispose-unsubscribe-255x300.png 255w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-state-container-onchange-dispose-unsubscribe-871x1024.png 871w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-state-container-onchange-dispose-unsubscribe-768x903.png 768w" sizes="auto, (max-width: 1184px) 100vw, 1184px" /><figcaption class="wp-element-caption">The badge refreshes, and Dispose removes the handler when the page goes away</figcaption></figure>
</div>


<p class="wp-block-paragraph">The <code>(Static)</code> line is the discarded prerendered copy. Skip the <code>-=</code> and the service holds every dead badge, the leak the <a href="https://aspdotnethelp.com/dispose-and-finalize-in-csharp/">Dispose pattern</a> prevents.</p>



<h2 class="wp-block-heading">Why Doesn&#8217;t the Parent Component Refresh When a Child Changes Data?</h2>



<p class="wp-block-paragraph">Same root cause, other direction. <code>Pickups.razor</code> shows a count, and each <code>ReadyButton</code> child reports back through an <code>Action&lt;string&gt;</code> parameter:</p>



<pre class="wp-block-code"><code>
@page &quot;/pickups&quot;
@rendermode InteractiveServer

&lt;PageTitle&gt;Pickups&lt;/PageTitle&gt;

&lt;h1&gt;Ready for pickup: @ready.Count&lt;/h1&gt;
&lt;p&gt;@(ready.Count == 0 ? &quot;No orders yet&quot; : string.Join(&quot;, &quot;, ready))&lt;/p&gt;

&lt;ReadyButton OrderNumber=&quot;#1043&quot; OnReady=&quot;AddReady&quot; /&gt;
&lt;ReadyButton OrderNumber=&quot;#1044&quot; OnReady=&quot;AddReady&quot; /&gt;

@code {
    private readonly List&lt;string&gt; ready = [];

    private void AddReady(string order)
    {
        ready.Add(order);
        Console.WriteLine($&quot;Pickups.AddReady: {order} ({ready.Count} ready)&quot;);
    }
}
</code></pre>



<pre class="wp-block-code"><code>
&lt;button class=&quot;btn btn-success me-2&quot; data-order=&quot;@OrderNumber&quot; disabled=&quot;@done&quot; @onclick=&quot;MarkReady&quot;&gt;
    @(done ? $&quot;{OrderNumber} marked&quot; : $&quot;Mark {OrderNumber} ready&quot;)
&lt;/button&gt;

@code {
    private bool done;

    [Parameter] public string OrderNumber { get; set; } = &quot;&quot;;
    [Parameter] public Action&lt;string&gt;? OnReady { get; set; }

    private void MarkReady()
    {
        done = true;
        OnReady?.Invoke(OrderNumber);
    }
}
</code></pre>



<p class="wp-block-paragraph">Two clicks: the console said <code>Pickups.AddReady: #1044 (2 ready)</code>, both buttons switched to &#8220;marked&#8221;, and the heading still said 0. The parent&#8217;s method ran, but the event belonged to the child.</p>



<p class="wp-block-paragraph">Change the parameter to <code>EventCallback&lt;string&gt;</code>. Blazor then re-renders the parent after the callback, no <code>StateHasChanged</code> needed:</p>



<pre class="wp-block-code"><code>    [Parameter] public EventCallback&lt;string&gt; OnReady { get; set; }

    private async Task MarkReady()
    {
        done = true;
        await OnReady.InvokeAsync(OrderNumber);
    }</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1012" height="244" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-eventcallback-parent-refresh-before-after.png" alt="Before and after in Edge: Ready for pickup: 0 with an Action parameter, Ready for pickup: 2 after switching the child parameter to EventCallback" class="wp-image-3157" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-eventcallback-parent-refresh-before-after.png 1012w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-eventcallback-parent-refresh-before-after-300x72.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-eventcallback-parent-refresh-before-after-768x185.png 768w" sizes="auto, (max-width: 1012px) 100vw, 1012px" /><figcaption class="wp-element-caption">Left: Action<string>. Right: EventCallback<string> refreshes the parent</figcaption></figure>
</div>


<p class="wp-block-paragraph">The parent markup didn&#8217;t change. My <a href="https://aspdotnethelp.com/blazor-components/">Blazor components guide</a> covers parameters in depth.</p>



<h2 class="wp-block-heading">StateHasChanged Inside a Loop: Show Progress From an Async Handler</h2>



<p class="wp-block-paragraph"><code>Import.razor</code> saves five orders, 600 ms each. Without the <code>StateHasChanged()</code> line in the loop, the page showed &#8220;Idle&#8221; at 2.1 seconds and jumped straight to &#8220;Done: 5 orders imported&#8221; at the end:</p>



<pre class="wp-block-code"><code>
@page &quot;/import&quot;
@rendermode InteractiveServer

&lt;PageTitle&gt;Import&lt;/PageTitle&gt;

&lt;h1&gt;Import Orders&lt;/h1&gt;
&lt;p class=&quot;fs-5&quot;&gt;Status: &lt;strong id=&quot;status&quot;&gt;@status&lt;/strong&gt;&lt;/p&gt;
&lt;button class=&quot;btn btn-primary&quot; id=&quot;import&quot; @onclick=&quot;ImportAsync&quot;&gt;Import 5 orders&lt;/button&gt;
&lt;button class=&quot;btn btn-outline-secondary&quot; id=&quot;total&quot; @onclick=&quot;LoadTotal&quot;&gt;Load today&#x27;s total&lt;/button&gt;

@code {
    private string status = &quot;Idle&quot;;

    private async Task ImportAsync()
    {
        for (int i = 1; i &lt;= 5; i++)
        {
            await Task.Delay(600);   // stands in for saving one order
            status = $&quot;Imported {i} of 5&quot;;
            StateHasChanged();       // render the progress now
        }
        status = &quot;Done: 5 orders imported&quot;;
    }

    private async void LoadTotal()
    {
        status = &quot;Loading total...&quot;;
        await Task.Delay(500);
        status = &quot;Total today: $1,284.50&quot;;
    }
}
</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1012" height="244" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-statehaschanged-loop-progress-before-after.png" alt="Before and after in Edge at 2.1 seconds into the import: Status Idle without StateHasChanged in the loop, Imported 4 of 5 with it" class="wp-image-3161" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-statehaschanged-loop-progress-before-after.png 1012w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-statehaschanged-loop-progress-before-after-300x72.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-statehaschanged-loop-progress-before-after-768x185.png 768w" sizes="auto, (max-width: 1012px) 100vw, 1012px" /><figcaption class="wp-element-caption">Same moment, with and without StateHasChanged() in the loop</figcaption></figure>
</div>


<p class="wp-block-paragraph">With the line, the same moment read &#8220;Imported 4 of 5&#8221;. Each <a href="https://aspdotnethelp.com/async-await-in-csharp/">await</a> gives the renderer a chance to draw what <code>StateHasChanged</code> queued. Five calls with no await between them still render once.</p>



<h2 class="wp-block-heading">async void Event Handlers Stop Blazor From Refreshing</h2>



<p class="wp-block-paragraph">The second button on that page is <code>async void LoadTotal()</code>. One click, 1.5 seconds later, and the status still read &#8220;Loading total&#8230;&#8221;. Blazor rendered after the synchronous part and had no task to wait for, so the final value never reached the page.</p>



<p class="wp-block-paragraph">Changing the signature to <code>async Task</code> fixed it with no other change: the page showed &#8220;Total today: $1,284.50&#8221;.</p>



<pre class="wp-block-code"><code>    private async Task LoadTotal()</code></pre>



<p class="wp-block-paragraph"><strong>Note:</strong> an exception in an <code>async void</code> method also skips Blazor&#8217;s error handling.</p>



<h2 class="wp-block-heading">ShouldRender and Static Render Mode Block StateHasChanged</h2>



<p class="wp-block-paragraph">If <code>StateHasChanged</code> runs and nothing happens, check for a <code>ShouldRender</code> override. When it returns <code>false</code>, Blazor skips the render (only the very first render is guaranteed):</p>



<pre class="wp-block-code"><code>protected override bool ShouldRender() =&gt; shouldRender;</code></pre>



<p class="wp-block-paragraph">The other blocker is render mode. I removed <code>@rendermode InteractiveServer</code> from the template&#8217;s Counter page and clicked the button three times: it still said &#8220;Current count: 0&#8221;, since static SSR has no circuit and runs no handlers. My <a href="https://aspdotnethelp.com/blazor-render-modes/">Blazor render modes guide</a> covers the options.</p>



<h2 class="wp-block-heading">Infinite Render Loop: StateHasChanged in OnAfterRender</h2>



<p class="wp-block-paragraph"><code>OnAfterRender</code> runs after every render, so calling <code>StateHasChanged</code> there unconditionally queues another render, forever. The method in <code>RenderLoop.razor</code>:</p>



<pre class="wp-block-code"><code>protected override void OnAfterRender(bool firstRender)
{
        renders++;
        if (renders % 2000 == 0)
            Console.WriteLine($&quot;OnAfterRender call #{renders}&quot;);
        StateHasChanged();   // BUG: every render queues another render
}</code></pre>



<p class="wp-block-paragraph">About a second after the circuit connected, the page said &#8220;Renders: 2325&#8221; and the console was still counting:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1184" height="1392" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-statehaschanged-onafterrender-infinite-loop.png" alt="VS Code with RenderLoop.razor open and the terminal printing OnAfterRender call numbers in the thousands from a StateHasChanged call inside OnAfterRender" class="wp-image-3164" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-statehaschanged-onafterrender-infinite-loop.png 1184w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-statehaschanged-onafterrender-infinite-loop-255x300.png 255w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-statehaschanged-onafterrender-infinite-loop-871x1024.png 871w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-statehaschanged-onafterrender-infinite-loop-768x903.png 768w" sizes="auto, (max-width: 1184px) 100vw, 1184px" /><figcaption class="wp-element-caption">StateHasChanged() in OnAfterRender: thousands of renders in seconds</figcaption></figure>
</div>


<p class="wp-block-paragraph">Guard it with <code>firstRender</code>, the same check you use for <a href="https://aspdotnethelp.com/blazor-javascript-interop/">JavaScript interop</a> setup:</p>



<pre class="wp-block-code"><code>        renders++;
        Console.WriteLine($&quot;OnAfterRender call #{renders}&quot;);
        if (firstRender)
            StateHasChanged();   // one extra render, then it stops</code></pre>



<p class="wp-block-paragraph">Now the log shows <code>OnAfterRender call #1</code> and <code>OnAfterRender call #2</code>, then stops. Microsoft Learn notes that a task returned from <code>OnAfterRenderAsync</code> never triggers a render either, for this exact reason.</p>



<h2 class="wp-block-heading">Which StateHasChanged Fix Do You Need?</h2>



<figure class="wp-block-table"><table><thead><tr><th>Symptom</th><th>Fix</th></tr></thead><tbody><tr><td>Timer, <code>Task.Run</code> or background work changes a field</td><td><code>InvokeAsync(StateHasChanged)</code></td></tr><tr><td>&#8220;The current thread is not associated with the Dispatcher&#8221;</td><td>Same: wrap the update in <code>InvokeAsync</code></td></tr><tr><td>A sibling component doesn&#8217;t update</td><td>Service event + <code>StateHasChanged</code>, unsubscribe in <code>Dispose</code></td></tr><tr><td>Parent doesn&#8217;t update after a child change</td><td><code>EventCallback&lt;T&gt;</code> instead of <code>Action&lt;T&gt;</code></td></tr><tr><td>Progress only shows at the end</td><td><code>StateHasChanged()</code> after each <code>await</code></td></tr><tr><td>Final value never shows</td><td><code>async Task</code>, never <code>async void</code></td></tr><tr><td>Buttons do nothing</td><td>Add an interactive render mode</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Regular event handlers and <a href="https://aspdotnethelp.com/blazor-forms-validation/">form submits</a> need none of this; extra calls only cost renders.</p>



<p class="wp-block-paragraph">If you&#8217;re building more Blazor pages, these are good next reads:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/blazor-tutorials/">Every Blazor tutorial on the site, in order</a></li>

<li><a href="https://aspdotnethelp.com/blazor-quickgrid/">Show the live orders in a sortable QuickGrid</a></li>

<li><a href="https://aspdotnethelp.com/blazor-server-vs-webassembly/">Blazor Server vs WebAssembly: which hosting model to pick</a></li>

<li><a href="https://aspdotnethelp.com/whats-new-in-dotnet-10/">What&#8217;s new in .NET 10</a></li>
</ul>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-shc0000001" class="rank-math-list-item">
<h3 class="rank-math-question ">Why is StateHasChanged not refreshing my Blazor component?</h3>
<div class="rank-math-answer ">

<p>Usually one of four things: the call runs off Blazor&#8217;s dispatcher (use InvokeAsync), a different component needs the refresh, ShouldRender returns false, or the page has no interactive render mode. See <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/components/rendering?view=aspnetcore-10.0" target="_blank" rel="noopener">ASP.NET Core Razor component rendering</a> on Microsoft Learn.</p>

</div>
</div>
<div id="faq-question-shc0000002" class="rank-math-list-item">
<h3 class="rank-math-question ">What is the difference between StateHasChanged and InvokeAsync(StateHasChanged)?</h3>
<div class="rank-math-answer ">

<p>StateHasChanged queues a render and must run on the renderer&#8217;s synchronization context. InvokeAsync first switches to that context, so InvokeAsync(StateHasChanged) is safe from timers, Task.Run and service events raised on other threads.</p>

</div>
</div>
<div id="faq-question-shc0000003" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I refresh a child component in Blazor?</h3>
<div class="rank-math-answer ">

<p>Pass it new parameter values from the parent; the child re-renders when they change. For a component that isn&#8217;t a child, use a shared state service with an event the component subscribes to.</p>

</div>
</div>
<div id="faq-question-shc0000004" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I refresh the whole page in Blazor?</h3>
<div class="rank-math-answer ">

<p>Call NavigationManager.Refresh() (.NET 8 and later). Refresh(forceReload: true) always does a full reload; otherwise the new HTML may be merged into the current page.</p>

</div>
</div>
<div id="faq-question-shc0000005" class="rank-math-list-item">
<h3 class="rank-math-question ">Why do I get &#8220;The current thread is not associated with the Dispatcher&#8221;?</h3>
<div class="rank-math-answer ">

<p>You called StateHasChanged, or changed rendered state, from a thread Blazor doesn&#8217;t own. Wrap the code in InvokeAsync, as the <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/components/synchronization-context?view=aspnetcore-10.0" target="_blank" rel="noopener">Blazor synchronization context</a> docs show.</p>

</div>
</div>
</div>
</div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ToDictionary and ToLookup in C#: Convert a List to a Dictionary</title>
		<link>https://aspdotnethelp.com/todictionary-tolookup-in-csharp/</link>
		
		<dc:creator><![CDATA[Bijay Kumar]]></dc:creator>
		<pubDate>Sun, 29 Nov 2026 21:20:00 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=3111</guid>

					<description><![CDATA[Pass a key selector and C# LINQ ToDictionary turns a list into a Dictionary&#60;TKey, TValue&#62; in one call. Here the customer ID becomes the key: The catch is that two items can&#8217;t share a key. I ran the duplicate-key crash, three fixes and ToLookup for one-to-many data on .NET 10 with five US customers. C# ... <a title="ToDictionary and ToLookup in C#: Convert a List to a Dictionary" class="read-more" href="https://aspdotnethelp.com/todictionary-tolookup-in-csharp/" aria-label="Read more about ToDictionary and ToLookup in C#: Convert a List to a Dictionary">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Pass a key selector and <strong>C# LINQ ToDictionary</strong> turns a list into a <code>Dictionary&lt;TKey, TValue&gt;</code> in one call. Here the customer ID becomes the key:</p>



<pre class="wp-block-code"><code>var byId = Customers.ToDictionary(c =&gt; c.Id);
Console.WriteLine(byId[102].Name);   // Tyler Brooks</code></pre>



<p class="wp-block-paragraph">The catch is that two items can&#8217;t share a key. I ran the duplicate-key crash, three fixes and <code>ToLookup</code> for one-to-many data on .NET 10 with five US customers.</p>



<h2 class="wp-block-heading">C# LINQ ToDictionary Syntax and Overloads</h2>



<p class="wp-block-paragraph"><code>ToDictionary</code> lives in <code>System.Linq</code> and runs right away, unlike most <a href="https://aspdotnethelp.com/linq-in-csharp/">LINQ operators</a>. These are the calls you&#8217;ll actually use:</p>



<figure class="wp-block-table"><table><thead><tr><th>Call</th><th>Builds</th><th>Since</th></tr></thead><tbody><tr><td><code>list.ToDictionary(x =&gt; x.Id)</code></td><td>Key -&gt; the whole item</td><td>Any .NET</td></tr><tr><td><code>list.ToDictionary(x =&gt; x.Id, x =&gt; x.Name)</code></td><td>Key -&gt; a value you pick</td><td>Any .NET</td></tr><tr><td><code>ToDictionary(keySelector, comparer)</code></td><td>Custom key equality (ignore case)</td><td>Any .NET</td></tr><tr><td><code>pairs.ToDictionary()</code></td><td>From KeyValuePair or (key, value) tuples</td><td>.NET 8+</td></tr><tr><td><code>list.ToLookup(x =&gt; x.State)</code></td><td>Key -&gt; many items</td><td>Any .NET</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Every demo includes this Data.cs and runs as a .NET 10 <a href="https://aspdotnethelp.com/dotnet-run-file-based-apps/">file-based app</a> with <code>dotnet run</code>:</p>



<pre class="wp-block-code"><code>using System.Globalization;

public record Customer(int Id, string Name, string City, string State, string Zip);
public record Order(int OrderId, int CustomerId, decimal Total);

public static class Shop
{
    public static List&lt;Customer&gt; Customers =
    [
        new(101, &quot;Jenna Morales&quot;, &quot;Austin&quot;, &quot;TX&quot;, &quot;78701&quot;),
        new(102, &quot;Tyler Brooks&quot;, &quot;Denver&quot;, &quot;CO&quot;, &quot;80202&quot;),
        new(103, &quot;Dana Whitfield&quot;, &quot;Albany&quot;, &quot;NY&quot;, &quot;12207&quot;),
        new(104, &quot;Marcus Lee&quot;, &quot;Dallas&quot;, &quot;TX&quot;, &quot;75201&quot;),
        new(105, &quot;Rachel Kim&quot;, &quot;Boulder&quot;, &quot;CO&quot;, &quot;80302&quot;),
    ];

    public static List&lt;Order&gt; Orders =
    [
        new(5001, 101, 129.99m), new(5002, 102, 48.50m),
        new(5003, 101, 310.00m), new(5004, 104, 75.25m),
    ];

    public static string Usd(decimal d) =&gt; d.ToString(&quot;C&quot;, CultureInfo.GetCultureInfo(&quot;en-US&quot;));
}</code></pre>



<p class="wp-block-paragraph">Notice that TX and CO each appear twice. That&#8217;s on purpose.</p>



<h2 class="wp-block-heading">Convert a List to a Dictionary with a Key and Element Selector</h2>



<p class="wp-block-paragraph">With one lambda, the value is the whole record. Add a second lambda (the element selector) to store just the part you need:</p>



<pre class="wp-block-code"><code>#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

Dictionary&lt;int, Customer&gt; byId = Customers.ToDictionary(c =&gt; c.Id);
Console.WriteLine($&quot;{byId.Count} customers, #102 is {byId[102].Name}&quot;);

Dictionary&lt;int, string&gt; cityById =
    Customers.ToDictionary(c =&gt; c.Id, c =&gt; $&quot;{c.City}, {c.State}&quot;);
foreach (var (id, city) in cityById)
    Console.WriteLine($&quot;{id}: {city}&quot;);

var totals = Orders.ToDictionary(o =&gt; o.OrderId, o =&gt; o.Total);
Console.WriteLine($&quot;Order 5003 total: {Usd(totals[5003])}&quot;);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>5 customers, #102 is Tyler Brooks
101: Austin, TX
102: Denver, CO
103: Albany, NY
104: Dallas, TX
105: Boulder, CO
Order 5003 total: $310.00</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1184" height="1052" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-linq-todictionary-key-selector-element-selector-vscode.png" alt="C# LINQ ToDictionary in VS Code: a customer list keyed by Id, an element selector mapping Id to city and state, and order totals in USD" class="wp-image-3142" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-linq-todictionary-key-selector-element-selector-vscode.png 1184w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-linq-todictionary-key-selector-element-selector-vscode-300x267.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-linq-todictionary-key-selector-element-selector-vscode-1024x910.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-linq-todictionary-key-selector-element-selector-vscode-768x682.png 768w" sizes="auto, (max-width: 1184px) 100vw, 1184px" /><figcaption class="wp-element-caption">ToDictionary with a key selector, then with an element selector</figcaption></figure>
</div>


<p class="wp-block-paragraph">You get 5 customers keyed by ID, a city map, and order 5003&#8217;s total of $310.00. Records make good values here; my <a href="https://aspdotnethelp.com/csharp-record-vs-class-vs-struct/">record vs class guide</a> explains why.</p>



<h2 class="wp-block-heading">Why Does ToDictionary Throw &#8220;An Item with the Same Key Has Already Been Added&#8221;?</h2>



<p class="wp-block-paragraph">Because a dictionary key must be unique, and <code>ToDictionary</code> doesn&#8217;t skip repeats. Key the same list by state and it fails on the second TX customer:</p>



<pre class="wp-block-code"><code>#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

try
{
    var byState = Customers.ToDictionary(c =&gt; c.State);
}
catch (ArgumentException ex)
{
    Console.WriteLine(ex.GetType().Name);
    Console.WriteLine(ex.Message);
}</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>ArgumentException
An item with the same key has already been added. Key: TX</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1184" height="1052" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-todictionary-argumentexception-same-key-already-added.png" alt="C# ToDictionary duplicate key error: ArgumentException An item with the same key has already been added. Key: TX in the VS Code terminal" class="wp-image-3143" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-todictionary-argumentexception-same-key-already-added.png 1184w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-todictionary-argumentexception-same-key-already-added-300x267.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-todictionary-argumentexception-same-key-already-added-1024x910.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-todictionary-argumentexception-same-key-already-added-768x682.png 768w" sizes="auto, (max-width: 1184px) 100vw, 1184px" /><figcaption class="wp-element-caption">The second TX customer stops the whole conversion</figcaption></figure>
</div>


<p class="wp-block-paragraph">On .NET 10 the message ends with the key (TX), which makes the bad row easy to find. I&#8217;d catch it in a <a href="https://aspdotnethelp.com/try-catch-in-csharp/">try-catch block</a> only for logging; the real fix is picking a strategy for duplicates.</p>



<h2 class="wp-block-heading">3 Ways to Fix Duplicate Keys in ToDictionary</h2>



<p class="wp-block-paragraph">Same list, same state key, three different answers to &#8220;what do I do with the second TX row?&#8221;:</p>



<pre class="wp-block-code"><code>#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

// Fix 1: GroupBy + First keeps the first customer per state
var first = Customers.GroupBy(c =&gt; c.State)
    .ToDictionary(g =&gt; g.Key, g =&gt; g.First().Name);
Console.WriteLine(&quot;GroupBy + First: &quot; + string.Join(&quot;, &quot;, first));

// Fix 2: DistinctBy drops repeated keys, then ToDictionary
var distinct = Customers.DistinctBy(c =&gt; c.State)
    .ToDictionary(c =&gt; c.State, c =&gt; c.Name);
Console.WriteLine(&quot;DistinctBy:      &quot; + string.Join(&quot;, &quot;, distinct));

// Fix 3: ToLookup keeps every customer per state
var all = Customers.ToLookup(c =&gt; c.State, c =&gt; c.Name);
foreach (var g in all)
    Console.WriteLine($&quot;ToLookup {g.Key}: {string.Join(&quot;, &quot;, g)}&quot;);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>GroupBy + First: [TX, Jenna Morales], [CO, Tyler Brooks], [NY, Dana Whitfield]
DistinctBy:      [TX, Jenna Morales], [CO, Tyler Brooks], [NY, Dana Whitfield]
ToLookup TX: Jenna Morales, Marcus Lee
ToLookup CO: Tyler Brooks, Rachel Kim
ToLookup NY: Dana Whitfield</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1184" height="1052" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-todictionary-duplicate-keys-groupby-distinctby-tolookup.png" alt="C# fix duplicate keys in ToDictionary with GroupBy and First, DistinctBy then ToDictionary, and ToLookup keeping both TX and CO customers" class="wp-image-3144" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-todictionary-duplicate-keys-groupby-distinctby-tolookup.png 1184w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-todictionary-duplicate-keys-groupby-distinctby-tolookup-300x267.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-todictionary-duplicate-keys-groupby-distinctby-tolookup-1024x910.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-todictionary-duplicate-keys-groupby-distinctby-tolookup-768x682.png 768w" sizes="auto, (max-width: 1184px) 100vw, 1184px" /><figcaption class="wp-element-caption">GroupBy + First and DistinctBy keep one row per state; ToLookup keeps all of them</figcaption></figure>
</div>


<ul class="wp-block-list">
<li><strong>GroupBy + First:</strong> one row per key, and you choose which one (<code>First</code>, <code>Last</code>, <code>MaxBy</code>).</li>

<li><strong>DistinctBy:</strong> the shortest way to keep the first row per key (.NET 6+). It&#8217;s covered in depth in <a href="https://aspdotnethelp.com/distinct-distinctby-in-csharp/">Distinct and DistinctBy in C#</a>.</li>

<li><strong>ToLookup:</strong> keep every row. TX holds Jenna Morales and Marcus Lee.</li>
</ul>



<p class="wp-block-paragraph">Both one-row fixes return Jenna for TX and Tyler for CO, because they keep the first match in list order.</p>



<h2 class="wp-block-heading">ToDictionary with StringComparer.OrdinalIgnoreCase</h2>



<p class="wp-block-paragraph">String keys are case-sensitive by default. Pass a comparer as the second argument when &#8220;denver&#8221; and &#8220;Denver&#8221; should be the same key:</p>



<pre class="wp-block-code"><code>#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

var byCity = Customers.ToDictionary(c =&gt; c.City, StringComparer.OrdinalIgnoreCase);
Console.WriteLine($&quot;denver -&gt; ZIP {byCity[&quot;denver&quot;].Zip}&quot;);
Console.WriteLine($&quot;BOULDER found: {byCity.ContainsKey(&quot;BOULDER&quot;)}&quot;);

var strict = Customers.ToDictionary(c =&gt; c.City);
Console.WriteLine($&quot;Default comparer, denver found: {strict.ContainsKey(&quot;denver&quot;)}&quot;);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>denver -&gt; ZIP 80202
BOULDER found: True
Default comparer, denver found: False</code></pre>



<p class="wp-block-paragraph">The ignore-case map finds &#8220;denver&#8221; (ZIP 80202) and &#8220;BOULDER&#8221;, while the default one says False for &#8220;denver&#8221;. Keep in mind that the comparer also turns &#8220;Austin&#8221; and &#8220;austin&#8221; into a duplicate key.</p>



<p class="wp-block-paragraph">The same comparer trick works anywhere you match text, as in <a href="https://aspdotnethelp.com/compare-string-with-multiple-values-in-csharp/">comparing a string with multiple values</a>.</p>



<h2 class="wp-block-heading">ToDictionary on a List of KeyValuePair or Tuples (.NET 8+)</h2>



<p class="wp-block-paragraph">If your data is already pairs, .NET 8 added a parameterless <code>ToDictionary()</code>. It works on <code>KeyValuePair</code> lists and on <code>(key, value)</code> <a href="https://aspdotnethelp.com/tuple-in-csharp/">value tuples</a>:</p>



<pre class="wp-block-code"><code>#:property PublishAot=false

List&lt;KeyValuePair&lt;string, string&gt;&gt; pairs =
[
    new(&quot;TX&quot;, &quot;Austin&quot;), new(&quot;CO&quot;, &quot;Denver&quot;), new(&quot;NY&quot;, &quot;Albany&quot;),
];
Dictionary&lt;string, string&gt; capitals = pairs.ToDictionary();
Console.WriteLine($&quot;KeyValuePair list: {capitals.Count} keys, TX = {capitals[&quot;TX&quot;]}&quot;);

(string Zip, string City)[] zips = [(&quot;78701&quot;, &quot;Austin&quot;), (&quot;80202&quot;, &quot;Denver&quot;)];
Dictionary&lt;string, string&gt; cityByZip = zips.ToDictionary();
Console.WriteLine($&quot;Tuple array: 80202 = {cityByZip[&quot;80202&quot;]}&quot;);

var noNewYork = capitals.Where(kv =&gt; kv.Key != &quot;NY&quot;).ToDictionary();
Console.WriteLine($&quot;Filtered copy: {string.Join(&quot;, &quot;, noNewYork.Keys)}&quot;);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>KeyValuePair list: 3 keys, TX = Austin
Tuple array: 80202 = Denver
Filtered copy: TX, CO</code></pre>



<p class="wp-block-paragraph">No lambdas needed. The last line is the handy one: filter a dictionary with <code>Where</code> and turn the result straight back into a dictionary. On .NET 7 or older, write <code>ToDictionary(kv =&gt; kv.Key, kv =&gt; kv.Value)</code> instead.</p>



<h2 class="wp-block-heading">ToLookup in C#: One Key, Many Values</h2>



<p class="wp-block-paragraph"><code>ToLookup</code> returns an <code>ILookup&lt;TKey, TElement&gt;</code>: a read-only, one-to-many dictionary. Same five customers, grouped by state:</p>



<pre class="wp-block-code"><code>#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

ILookup&lt;string, Customer&gt; byState = Customers.ToLookup(c =&gt; c.State);

Console.WriteLine($&quot;States: {byState.Count}&quot;);
Console.WriteLine($&quot;TX customers: {byState[&quot;TX&quot;].Count()}&quot;);
foreach (var c in byState[&quot;CO&quot;])
    Console.WriteLine($&quot;  CO: {c.Name} ({c.Zip})&quot;);

IEnumerable&lt;Customer&gt; florida = byState[&quot;FL&quot;];   // no FL customers
Console.WriteLine($&quot;FL customers: {florida.Count()}&quot;);
Console.WriteLine($&quot;Contains(\&quot;FL\&quot;): {byState.Contains(&quot;FL&quot;)}&quot;);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>States: 3
TX customers: 2
  CO: Tyler Brooks (80202)
  CO: Rachel Kim (80302)
FL customers: 0
Contains(&quot;FL&quot;): False</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1184" height="1052" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-tolookup-ilookup-missing-key-empty-sequence.png" alt="C# ToLookup by state in VS Code: 3 states, 2 TX customers, the CO customers with ZIP codes, and a missing FL key returning 0 items" class="wp-image-3145" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-tolookup-ilookup-missing-key-empty-sequence.png 1184w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-tolookup-ilookup-missing-key-empty-sequence-300x267.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-tolookup-ilookup-missing-key-empty-sequence-1024x910.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-tolookup-ilookup-missing-key-empty-sequence-768x682.png 768w" sizes="auto, (max-width: 1184px) 100vw, 1184px" /><figcaption class="wp-element-caption">A missing key in an ILookup returns an empty sequence, not an exception</figcaption></figure>
</div>


<p class="wp-block-paragraph">You get 3 states and 2 TX customers. The best part is <code>byState["FL"]</code>: there&#8217;s no FL customer, so it returns an empty sequence instead of throwing. Use <code>Contains</code> when you need to know whether the key exists.</p>



<h2 class="wp-block-heading">ToLookup vs GroupBy: Immediate vs Deferred Execution</h2>



<p class="wp-block-paragraph">They look alike, but <code>ToLookup</code> builds its groups once, right away. <code>GroupBy</code> is deferred and regroups every time you enumerate it. A counter in the key selector proves it:</p>



<pre class="wp-block-code"><code>#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

int calls = 0;
var lookup = Customers.ToLookup(c =&gt; { calls++; return c.State; });
Console.WriteLine($&quot;After ToLookup: {calls} key calls&quot;);

calls = 0;
var groups = Customers.GroupBy(c =&gt; { calls++; return c.State; });
Console.WriteLine($&quot;After GroupBy:  {calls} key calls&quot;);
_ = groups.Count();
_ = groups.Count();
Console.WriteLine($&quot;After 2 loops:  {calls} key calls&quot;);

Customers.Add(new(106, &quot;Olivia Grant&quot;, &quot;Miami&quot;, &quot;FL&quot;, &quot;33101&quot;));
Console.WriteLine($&quot;Lookup FL: {lookup[&quot;FL&quot;].Count()}&quot;);
Console.WriteLine($&quot;GroupBy FL: {groups.Count(g =&gt; g.Key == &quot;FL&quot;)}&quot;);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>After ToLookup: 5 key calls
After GroupBy:  0 key calls
After 2 loops:  10 key calls
Lookup FL: 0
GroupBy FL: 1</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1184" height="1052" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-tolookup-vs-groupby-immediate-vs-deferred-key-calls.png" alt="C# ToLookup vs GroupBy proof: ToLookup calls the key selector 5 times immediately, GroupBy 0 times until enumerated and 10 times after two loops" class="wp-image-3146" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-tolookup-vs-groupby-immediate-vs-deferred-key-calls.png 1184w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-tolookup-vs-groupby-immediate-vs-deferred-key-calls-300x267.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-tolookup-vs-groupby-immediate-vs-deferred-key-calls-1024x910.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-tolookup-vs-groupby-immediate-vs-deferred-key-calls-768x682.png 768w" sizes="auto, (max-width: 1184px) 100vw, 1184px" /><figcaption class="wp-element-caption">ToLookup runs once up front; GroupBy re-runs on every loop and sees the new FL customer</figcaption></figure>
</div>


<p class="wp-block-paragraph"><code>ToLookup</code> made 5 key calls up front. <code>GroupBy</code> made 0 until I looped, then 10 after two loops. After I added a Miami customer, the lookup still said 0 for FL and <code>GroupBy</code> said 1.</p>



<p class="wp-block-paragraph"><strong>Pro Tip:</strong> if you&#8217;ll read the groups more than once, call <code>ToLookup</code> (or <code>ToList</code>) once and reuse it. My <a href="https://aspdotnethelp.com/linq-groupby-in-csharp/">LINQ GroupBy guide</a> shows more group shapes.</p>



<h2 class="wp-block-heading">ToLookup vs Dictionary&lt;TKey, List&lt;T&gt;&gt;</h2>



<p class="wp-block-paragraph">A dictionary of lists does the same grouping, but you can change it later. Here&#8217;s the trade-off on the same data:</p>



<pre class="wp-block-code"><code>#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

Dictionary&lt;string, List&lt;Customer&gt;&gt; byState = Customers
    .GroupBy(c =&gt; c.State)
    .ToDictionary(g =&gt; g.Key, g =&gt; g.ToList());

byState[&quot;TX&quot;].Add(new(106, &quot;Olivia Grant&quot;, &quot;Houston&quot;, &quot;TX&quot;, &quot;77002&quot;));
Console.WriteLine($&quot;Dictionary TX after Add: {byState[&quot;TX&quot;].Count}&quot;);

try { _ = byState[&quot;FL&quot;]; }
catch (KeyNotFoundException) { Console.WriteLine(&quot;Dictionary FL: KeyNotFoundException&quot;); }

ILookup&lt;string, Customer&gt; lookup = Customers.ToLookup(c =&gt; c.State);
Console.WriteLine($&quot;Lookup FL: {lookup[&quot;FL&quot;].Count()} items, no exception&quot;);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>Dictionary TX after Add: 3
Dictionary FL: KeyNotFoundException
Lookup FL: 0 items, no exception</code></pre>



<figure class="wp-block-table"><table><thead><tr><th></th><th>ILookup&lt;K, T&gt;</th><th>Dictionary&lt;K, List&lt;T&gt;&gt;</th></tr></thead><tbody><tr><td>Add items later</td><td>No (read-only)</td><td>Yes, <code>dict[key].Add(...)</code></td></tr><tr><td>Missing key</td><td>Empty sequence</td><td><code>KeyNotFoundException</code></td></tr><tr><td>Built with</td><td><code>ToLookup</code></td><td><code>GroupBy</code> + <code>ToDictionary</code></td></tr></tbody></table></figure>



<p class="wp-block-paragraph">I reach for <code>ToLookup</code> when I group once and only read. When orders keep arriving, the dictionary of lists wins. The <a href="https://aspdotnethelp.com/dictionary-in-csharp/">C# Dictionary guide</a> covers <code>TryGetValue</code> for the missing-key case.</p>



<h2 class="wp-block-heading">ToFrozenDictionary for Read-Only Lookups (.NET 8+)</h2>



<p class="wp-block-paragraph">For a map you build once at startup and read millions of times, <code>System.Collections.Frozen</code> has <code>ToFrozenDictionary</code>. It&#8217;s slower to create but tuned for fast reads:</p>



<pre class="wp-block-code"><code>#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

using System.Collections.Frozen;

FrozenDictionary&lt;string, Customer&gt; byZip = Customers.ToFrozenDictionary(c =&gt; c.Zip);
Console.WriteLine($&quot;80302: {byZip[&quot;80302&quot;].Name}, {byZip[&quot;80302&quot;].City}&quot;);
Console.WriteLine($&quot;33101 found: {byZip.ContainsKey(&quot;33101&quot;)}&quot;);

List&lt;KeyValuePair&lt;string, string&gt;&gt; pairs = [new(&quot;TX&quot;, &quot;Austin&quot;), new(&quot;TX&quot;, &quot;Dallas&quot;)];
Console.WriteLine($&quot;Pairs with a repeated key: TX = {pairs.ToFrozenDictionary()[&quot;TX&quot;]}&quot;);

try { Customers.ToFrozenDictionary(c =&gt; c.State); Console.WriteLine(&quot;Key selector: no exception&quot;); }
catch (ArgumentException ex) { Console.WriteLine($&quot;Key selector: {ex.Message}&quot;); }</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>80302: Rachel Kim, Boulder
33101 found: False
Pairs with a repeated key: TX = Dallas
Key selector: An item with the same key has already been added. Key: TX</code></pre>



<p class="wp-block-paragraph">Lookups work like any dictionary: 80302 is Rachel Kim in Boulder, and 33101 isn&#8217;t there. The surprise is duplicates: the pair overload kept the last TX value (Dallas), and the key-selector overload threw the usual duplicate-key error.</p>



<h2 class="wp-block-heading">Convert a List to a Dictionary Without LINQ (foreach + TryAdd)</h2>



<p class="wp-block-paragraph">Sometimes a plain loop is clearer, especially when you want to log each duplicate. <code>TryAdd</code> returns false instead of throwing, and the indexer overwrites. The basics of the source collection are in my <a href="https://aspdotnethelp.com/list-in-csharp/">List in C# guide</a>:</p>



<pre class="wp-block-code"><code>#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

var byState = new Dictionary&lt;string, Customer&gt;();
foreach (var c in Customers)
{
    if (!byState.TryAdd(c.State, c))
        Console.WriteLine($&quot;Skipped {c.Name}: {c.State} is already taken&quot;);
}
Console.WriteLine($&quot;{byState.Count} states: {string.Join(&quot;, &quot;, byState.Keys)}&quot;);

var lastWins = new Dictionary&lt;string, string&gt;();
foreach (var c in Customers)
    lastWins[c.State] = c.Name;          // the indexer overwrites
Console.WriteLine($&quot;Indexer keeps the last: TX = {lastWins[&quot;TX&quot;]}&quot;);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>Skipped Marcus Lee: TX is already taken
Skipped Rachel Kim: CO is already taken
3 states: TX, CO, NY
Indexer keeps the last: TX = Marcus Lee</code></pre>



<p class="wp-block-paragraph"><code>TryAdd</code> skips Marcus Lee and Rachel Kim and keeps 3 states (first wins). The indexer version keeps the last one, so TX ends up as Marcus Lee.</p>



<p class="wp-block-paragraph">For more on working with collections, these pair well with this one:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/linq-join-in-csharp/">LINQ Join in C#: inner, left and GroupJoin</a></li>

<li><a href="https://aspdotnethelp.com/collection-expressions-in-csharp/">Collection expressions in C#</a></li>

<li><a href="https://aspdotnethelp.com/hashtable-in-csharp/">Hashtable in C# (and why Dictionary replaced it)</a></li>

<li><a href="https://aspdotnethelp.com/system-text-json-in-csharp/">Serialize a dictionary to JSON with System.Text.Json</a></li>
</ul>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-31110000001" class="rank-math-list-item">
<h3 class="rank-math-question ">What is the difference between ToDictionary and ToLookup in C#?</h3>
<div class="rank-math-answer ">

<p><code>ToDictionary</code> maps each key to exactly one value and throws on a duplicate key. <code>ToLookup</code> maps each key to a sequence of values, accepts repeated keys, and returns an empty sequence for a key that isn&#8217;t there.</p>

</div>
</div>
<div id="faq-question-31110000002" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I convert a list to a dictionary when keys might repeat?</h3>
<div class="rank-math-answer ">

<p>Decide which row wins: <code>GroupBy(x =&gt; x.Key).ToDictionary(g =&gt; g.Key, g =&gt; g.First())</code> keeps the first, <code>DistinctBy(x =&gt; x.Key)</code> does the same in one step, and <code>ToLookup</code> keeps them all.</p>

</div>
</div>
<div id="faq-question-31110000003" class="rank-math-list-item">
<h3 class="rank-math-question ">Does ToDictionary keep the order of my list?</h3>
<div class="rank-math-answer ">

<p>Don&#8217;t rely on it. <code>Dictionary&lt;TKey, TValue&gt;</code> doesn&#8217;t promise an enumeration order. Freshly built dictionaries usually return items in insertion order, but sort the keys when the order matters.</p>

</div>
</div>
<div id="faq-question-31110000004" class="rank-math-list-item">
<h3 class="rank-math-question ">Can a key from ToDictionary be null?</h3>
<div class="rank-math-answer ">

<p>No. If the key selector returns null, <code>ToDictionary</code> throws <code>ArgumentNullException</code>. The <a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.todictionary?view=net-10.0" target="_blank" rel="noopener">Enumerable.ToDictionary reference on Microsoft Learn</a> lists every overload and exception.</p>

</div>
</div>
<div id="faq-question-31110000005" class="rank-math-list-item">
<h3 class="rank-math-question ">Is the ILookup returned by ToLookup editable?</h3>
<div class="rank-math-answer ">

<p>No. <code>ILookup</code> has no Add or Remove. Rebuild it, or use a <code>Dictionary&lt;TKey, List&lt;T&gt;&gt;</code>. See the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.tolookup?view=net-10.0" target="_blank" rel="noopener">Enumerable.ToLookup docs</a> for its overloads.</p>

</div>
</div>
</div>
</div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Logging in ASP.NET Core: ILogger, Log Levels and Serilog to a File</title>
		<link>https://aspdotnethelp.com/logging-in-aspnet-core/</link>
		
		<dc:creator><![CDATA[Bijay Kumar]]></dc:creator>
		<pubDate>Sun, 29 Nov 2026 15:15:00 +0000</pubDate>
				<category><![CDATA[ASP.NET Core]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=3110</guid>

					<description><![CDATA[Say a customer in Denver gets a 500 at checkout from your orders API, and the console window that showed why is already gone. ASP.NET Core logging to file fixes that: keep the built-in ILogger in your code, set log levels in appsettings.json, and add Serilog with a rolling file sink, because ASP.NET Core has ... <a title="Logging in ASP.NET Core: ILogger, Log Levels and Serilog to a File" class="read-more" href="https://aspdotnethelp.com/logging-in-aspnet-core/" aria-label="Read more about Logging in ASP.NET Core: ILogger, Log Levels and Serilog to a File">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Say a customer in Denver gets a 500 at checkout from your orders API, and the console window that showed why is already gone.</p>



<p class="wp-block-paragraph"><strong>ASP.NET Core logging to file</strong> fixes that: keep the built-in <code>ILogger</code> in your code, set log levels in appsettings.json, and add Serilog with a rolling file sink, because ASP.NET Core has no file provider of its own.</p>



<p class="wp-block-paragraph">I built that orders API on .NET 10 and ran it at every log level, so each output below is real.</p>



<h2 class="wp-block-heading">The Sample Orders API for ASP.NET Core Logging</h2>



<p class="wp-block-paragraph">Here&#8217;s the running sample. It&#8217;s a minimal API called W12OrdersApi with one endpoint, /checkout/{id}, and two orders:</p>



<ul class="wp-block-list">
<li><strong>1042</strong>: Jenna Morales in Texas, $1,249.50. A normal checkout that should log one Information line.</li>

<li><strong>1043</strong>: Tyler Brooks in Colorado, $6,480.00. It&#8217;s over a $5,000 review limit (a Warning), and its payment times out (an Error and a 500).</li>
</ul>



<p class="wp-block-paragraph">The 1043 order is the tricky one. It&#8217;s the request you&#8217;ll need to find in a log file at 2 AM, so every method below has to show it clearly.</p>



<p class="wp-block-paragraph">The project file needs no extra packages for the built-in logger:</p>



<pre class="wp-block-code"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
  &lt;/PropertyGroup&gt;

&lt;/Project&gt;</code></pre>



<h2 class="wp-block-heading">Method 1: Built-in ILogger&lt;T&gt; Logging in ASP.NET Core (Recommended Start)</h2>



<p class="wp-block-paragraph">Start here even if you plan to add Serilog later. <code>WebApplication.CreateBuilder</code> already registers logging, so any class can ask for <code>ILogger&lt;T&gt;</code> through dependency injection. Your code never knows which provider writes the lines.</p>



<p class="wp-block-paragraph">Here&#8217;s OrderService.cs. It takes the logger through a <a href="https://aspdotnethelp.com/primary-constructors-in-csharp/">C# primary constructor</a> and writes one message per level:</p>



<pre class="wp-block-code"><code>public record Order(int Id, string Customer, string State, decimal Total);

public class OrderService(ILogger&lt;OrderService&gt; logger)
{
    private readonly Dictionary&lt;int, Order&gt; orders = new()
    {
        [1042] = new(1042, &quot;Jenna Morales&quot;, &quot;TX&quot;, 1249.50m),
        [1043] = new(1043, &quot;Tyler Brooks&quot;, &quot;CO&quot;, 6480.00m),
    };

    public IResult Checkout(int id)
    {
        logger.LogTrace(&quot;Checkout started for order {OrderId}&quot;, id);
        var order = orders[id];
        using var scope = logger.BeginScope(&quot;Customer {Customer} in {State}&quot;, order.Customer, order.State);
        logger.LogDebug(&quot;Order {OrderId} total is ${Total}&quot;, id, order.Total);
        if (order.Total &gt; 5000m)
            logger.LogWarning(&quot;Order {OrderId} is over the $5,000 review limit&quot;, id);
        try
        {
            if (id == 1043) throw new TimeoutException(&quot;Payment gateway did not answer in 30 seconds&quot;);
            logger.LogInformation(&quot;Order {OrderId} placed for {Customer}&quot;, id, order.Customer);
            return Results.Ok(order);
        }
        catch (TimeoutException ex)
        {
            logger.LogError(ex, &quot;Payment failed for order {OrderId}&quot;, id);
            return Results.Problem(&quot;Payment failed&quot;, statusCode: 500);
        }
    }
}</code></pre>



<p class="wp-block-paragraph">Program.cs registers the service as a singleton (the <a href="https://aspdotnethelp.com/dependency-injection-lifetimes-aspnet-core/">DI lifetimes guide</a> explains why that&#8217;s safe for a logger) and maps the endpoint:</p>



<pre class="wp-block-code"><code>var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton&lt;OrderService&gt;();

var app = builder.Build();
app.MapGet(&quot;/checkout/{id:int}&quot;, (int id, OrderService orders) =&gt; orders.Checkout(id));

app.Run();</code></pre>



<p class="wp-block-paragraph">And the appsettings.json the template gives you, plus a fixed URL on port 5900:</p>



<pre class="wp-block-code"><code>{
  &quot;Logging&quot;: {
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Information&quot;,
      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;
    }
  },
  &quot;AllowedHosts&quot;: &quot;*&quot;,
  &quot;Urls&quot;: &quot;http://localhost:5900&quot;
}</code></pre>



<p class="wp-block-paragraph">I ran <code>dotnet run --no-build</code> and called both orders with <code>curl http://localhost:5900/checkout/1042</code> and 1043. The console printed this after the startup lines:</p>



<pre class="wp-block-code"><code>info: OrderService[0]
      Order 1042 placed for Jenna Morales
warn: OrderService[0]
      Order 1043 is over the $5,000 review limit
fail: OrderService[0]
      Payment failed for order 1043
      System.TimeoutException: Payment gateway did not answer in 30 seconds
         at OrderService.Checkout(Int32 id) in C:\DotNetDemo\W12Logging\OrdersApi\OrderService.cs:line 21</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1492" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-ilogger-orderservice-console-log-levels-production.png" alt="ASP.NET Core ILogger in VS Code: OrderService.cs in the editor and the dotnet run console showing info, warn and fail log lines for orders 1042 and 1043" class="wp-image-3168" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-ilogger-orderservice-console-log-levels-production.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-ilogger-orderservice-console-log-levels-production-278x300.png 278w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-ilogger-orderservice-console-log-levels-production-950x1024.png 950w, https://aspdotnethelp.com/wp-content/uploads/2026/11/aspnet-core-ilogger-orderservice-console-log-levels-production-768x828.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">Production defaults: Information and above for OrderService, so Trace and Debug never show</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>How does this code work?</strong></p>



<p class="wp-block-paragraph">The category is the class name, so every line says <code>OrderService[0]</code>. The [0] is the event ID, which is 0 because I didn&#8217;t set one.</p>



<p class="wp-block-paragraph">Default is Information, so <code>LogTrace</code> and <code>LogDebug</code> were skipped for both orders. You got three lines: info for 1042, then warn and fail for 1043.</p>



<p class="wp-block-paragraph"><code>LogError(ex, ...)</code> takes the exception first, and the console printed the stack trace with the file and line number. For exceptions you don&#8217;t catch yourself, pair this with <a href="https://aspdotnethelp.com/aspnet-core-global-error-handling/">global error handling in ASP.NET Core</a>.</p>



<p class="wp-block-paragraph"><strong>Note:</strong> outside a class, use <code>app.Logger</code> in Program.cs. Its category is the app&#8217;s name.</p>



<h2 class="wp-block-heading">What Are the ASP.NET Core Logging Levels?</h2>



<p class="wp-block-paragraph">There are six levels plus None. A setting turns on that level and everything more severe:</p>



<figure class="wp-block-table"><table><thead><tr><th>Level</th><th>Value</th><th>Method</th><th>Use it for</th></tr></thead><tbody><tr><td>Trace</td><td>0</td><td><code>LogTrace</code></td><td>Step-by-step detail; off by default, never in production</td></tr><tr><td>Debug</td><td>1</td><td><code>LogDebug</code></td><td>Values you check while developing</td></tr><tr><td>Information</td><td>2</td><td><code>LogInformation</code></td><td>Normal flow: an order was placed</td></tr><tr><td>Warning</td><td>3</td><td><code>LogWarning</code></td><td>Unexpected but handled: over the review limit</td></tr><tr><td>Error</td><td>4</td><td><code>LogError</code></td><td>The current request failed: payment timeout</td></tr><tr><td>Critical</td><td>5</td><td><code>LogCritical</code></td><td>Needs someone now: data loss, disk full</td></tr><tr><td>None</td><td>6</td><td>&#8211;</td><td>Turns a category off</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Same orders, same two requests. I changed only the OrderService level with an environment variable (for example <code>set Logging__LogLevel__OrderService=Warning</code>) and noted what printed:</p>



<figure class="wp-block-table"><table><thead><tr><th>OrderService level</th><th>Console prefixes you see</th></tr></thead><tbody><tr><td>Trace</td><td>trce dbug info warn fail</td></tr><tr><td>Debug</td><td>dbug info warn fail</td></tr><tr><td>Information</td><td>info warn fail</td></tr><tr><td>Warning</td><td>warn fail</td></tr><tr><td>Error</td><td>fail</td></tr><tr><td>None</td><td>nothing</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">If a category has no setting at all, logging defaults to Information. Critical (crit) didn&#8217;t appear because nothing in the sample logs at that level.</p>



<h2 class="wp-block-heading">Filter Logging by Category in appsettings.json</h2>



<p class="wp-block-paragraph">Levels are set per category, and the longest matching prefix wins. That&#8217;s why the template&#8217;s <code>"Microsoft.AspNetCore": "Warning"</code> also covers <code>Microsoft.AspNetCore.Routing.EndpointMiddleware</code> and keeps request noise out.</p>



<p class="wp-block-paragraph">To see it, I dropped that category to Information for one run. A single checkout turned into this:</p>



<pre class="wp-block-code"><code>info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/1.1 GET http://localhost:5900/checkout/1042 - - -
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
      Executing endpoint &#x27;HTTP: GET /checkout/{id:int}&#x27;
info: OrderService[0]
      Order 1042 placed for Jenna Morales
info: Microsoft.AspNetCore.Http.Result.OkObjectResult[1]
      Setting HTTP status code 200.
info: Microsoft.AspNetCore.Http.Result.OkObjectResult[3]
      Writing value of type &#x27;Order&#x27; as Json.
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
      Executed endpoint &#x27;HTTP: GET /checkout/{id:int}&#x27;
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished HTTP/1.1 GET http://localhost:5900/checkout/1042 - 200 - application/json;+charset=utf-8 125.5060ms</code></pre>



<p class="wp-block-paragraph">Seven lines for one request, and only one of them is yours. Keep Microsoft.AspNetCore at Warning and get request lines from a single middleware instead, which is what Serilog does later. If you write your own, see <a href="https://aspdotnethelp.com/aspnet-core-middleware/">ASP.NET Core middleware</a>.</p>



<p class="wp-block-paragraph">For local work, turn up just your own code in appsettings.Development.json. Which file loads when is covered in <a href="https://aspdotnethelp.com/appsettings-per-environment-aspnet-core/">appsettings per environment in ASP.NET Core</a>, so I&#8217;ll only show the logging part:</p>



<pre class="wp-block-code"><code>{
  &quot;Logging&quot;: {
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Information&quot;,
      &quot;OrderService&quot;: &quot;Trace&quot;
    }
  }
}</code></pre>



<pre class="wp-block-code"><code>set &quot;ASPNETCORE_ENVIRONMENT=Development&quot;
dotnet run --no-build</code></pre>



<pre class="wp-block-code"><code>trce: OrderService[0]
      Checkout started for order 1042
dbug: OrderService[0]
      Order 1042 total is $1249.50
info: OrderService[0]
      Order 1042 placed for Jenna Morales
trce: OrderService[0]
      Checkout started for order 1043
dbug: OrderService[0]
      Order 1043 total is $6480.00
warn: OrderService[0]
      Order 1043 is over the $5,000 review limit
fail: OrderService[0]
      Payment failed for order 1043
      System.TimeoutException: Payment gateway did not answer in 30 seconds
         at OrderService.Checkout(Int32 id) in C:\DotNetDemo\W12Logging\OrdersApi\OrderService.cs:line 21</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1492" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/appsettings-development-json-logging-category-orderservice-trace.png" alt="appsettings.Development.json with OrderService set to Trace in VS Code, and the console showing trce and dbug lines for orders 1042 and 1043" class="wp-image-3167" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/appsettings-development-json-logging-category-orderservice-trace.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/appsettings-development-json-logging-category-orderservice-trace-278x300.png 278w, https://aspdotnethelp.com/wp-content/uploads/2026/11/appsettings-development-json-logging-category-orderservice-trace-950x1024.png 950w, https://aspdotnethelp.com/wp-content/uploads/2026/11/appsettings-development-json-logging-category-orderservice-trace-768x828.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">One category at Trace in Development: your code gets chatty, the framework stays quiet</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>How does this work?</strong></p>



<p class="wp-block-paragraph">The Development file merges on top of appsettings.json, so Default stays Information and the <code>OrderService</code> key adds a more specific rule. Now you see the trce and dbug lines, including the $6480.00 total for order 1043.</p>



<p class="wp-block-paragraph"><strong>Important:</strong> in environment variables, the colon becomes a double underscore, so <code>Logging:LogLevel:OrderService</code> is <code>Logging__LogLevel__OrderService</code>.</p>



<h2 class="wp-block-heading">Structured Logging: Message Templates vs String Interpolation (CA2254)</h2>



<p class="wp-block-paragraph">This is the mistake I see most. <code>$"Order {orderId} shipped"</code> looks fine, but the logger only gets the final string, so <code>OrderId</code> never becomes a field you can search on.</p>



<p class="wp-block-paragraph">The analyzer rule is CA2254, &#8220;Template should be a static expression.&#8221; In .NET 10 it&#8217;s on only as a suggestion, so nothing shows at build time. I raised it to a warning with an .editorconfig next to the file:</p>



<pre class="wp-block-code"><code>root = true

[*.cs]
dotnet_diagnostic.CA2254.severity = warning</code></pre>



<p class="wp-block-paragraph">Then a small <a href="https://aspdotnethelp.com/dotnet-run-file-based-apps/">file-based app</a> logs the same order twice, once each way, with the JSON console formatter:</p>



<pre class="wp-block-code"><code>#:package Microsoft.Extensions.Logging.Console@10.0.14
#:property PublishAot=false
using Microsoft.Extensions.Logging;

using var factory = LoggerFactory.Create(b =&gt; b.AddJsonConsole());
var logger = factory.CreateLogger(&quot;Orders&quot;);
int orderId = 1042;

logger.LogInformation($&quot;Order {orderId} shipped to Austin, TX&quot;);
logger.LogInformation(&quot;Order {OrderId} shipped to {City}, {State}&quot;, orderId, &quot;Austin&quot;, &quot;TX&quot;);</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>C:\DotNetDemo\W12Logging\Snippets\TemplateDemo.cs(9,23): warning CA2254: The logging message template should not vary between calls to &#x27;LoggerExtensions.LogInformation(ILogger, string?, params object?[])&#x27; (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2254)
{&quot;EventId&quot;:0,&quot;LogLevel&quot;:&quot;Information&quot;,&quot;Category&quot;:&quot;Orders&quot;,&quot;Message&quot;:&quot;Order 1042 shipped to Austin, TX&quot;,&quot;State&quot;:{&quot;{OriginalFormat}&quot;:&quot;Order 1042 shipped to Austin, TX&quot;}}
{&quot;EventId&quot;:0,&quot;LogLevel&quot;:&quot;Information&quot;,&quot;Category&quot;:&quot;Orders&quot;,&quot;Message&quot;:&quot;Order 1042 shipped to Austin, TX&quot;,&quot;State&quot;:{&quot;OrderId&quot;:1042,&quot;City&quot;:&quot;Austin&quot;,&quot;State&quot;:&quot;TX&quot;,&quot;{OriginalFormat}&quot;:&quot;Order {OrderId} shipped to {City}, {State}&quot;}}</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1492" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ca2254-logging-message-template-string-interpolation-warning.png" alt="CA2254 warning in VS Code: an interpolated string passed to LogInformation, and JSON console output where only the message template version has OrderId, City and State fields" class="wp-image-3169" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ca2254-logging-message-template-string-interpolation-warning.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ca2254-logging-message-template-string-interpolation-warning-278x300.png 278w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ca2254-logging-message-template-string-interpolation-warning-950x1024.png 950w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ca2254-logging-message-template-string-interpolation-warning-768x828.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">The interpolated call gets CA2254 and loses its fields; the template keeps OrderId, City and State</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>How does this code work?</strong></p>



<p class="wp-block-paragraph">Both lines print the same text. The difference is in <code>State</code>: the interpolated call stored only the finished sentence as <code>{OriginalFormat}</code>, while the template stored <code>OrderId</code> as the number 1042 plus City and State.</p>



<p class="wp-block-paragraph">Log tools like Seq, Elasticsearch or Application Insights index those fields. With them, &#8220;show every log for order 1043&#8221; is a filter, not a text search.</p>



<p class="wp-block-paragraph"><strong>Important:</strong> arguments fill placeholders by position, not by name, so keep them in the same order as the template.</p>



<h2 class="wp-block-heading">Method 2: LoggerMessage Source Generator for High-Performance Logging</h2>



<p class="wp-block-paragraph">For hot paths, mark a <code>partial</code> method with <code>[LoggerMessage]</code> and let the compiler write the logging code. Microsoft says it&#8217;s considerably faster at runtime because it avoids boxing and temporary allocations.</p>



<p class="wp-block-paragraph">Same order data, now as two generated log methods:</p>



<pre class="wp-block-code"><code>#:package Microsoft.Extensions.Logging.Console@10.0.14
#:property PublishAot=false
using Microsoft.Extensions.Logging;

using var factory = LoggerFactory.Create(b =&gt; b.AddSimpleConsole(o =&gt; o.SingleLine = true));
var logger = factory.CreateLogger(&quot;Orders&quot;);
logger.OrderShipped(1042, &quot;Austin&quot;, &quot;TX&quot;);
logger.ReviewNeeded(1043, 6480.00m);

static partial class OrderLog
{
    [LoggerMessage(EventId = 1001, Level = LogLevel.Information, Message = &quot;Order {OrderId} shipped to {City}, {State}&quot;)]
    public static partial void OrderShipped(this ILogger logger, int orderId, string city, string state);

    [LoggerMessage(EventId = 1002, Level = LogLevel.Warning, Message = &quot;Order {OrderId} needs review: ${Total}&quot;)]
    public static partial void ReviewNeeded(this ILogger logger, int orderId, decimal total);
}</code></pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="wp-block-code"><code>info: Orders[1001] Order 1042 shipped to Austin, TX
warn: Orders[1002] Order 1043 needs review: $6480.00</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1492" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/loggermessage-source-generator-partial-method-console-output.png" alt="LoggerMessage source generator in VS Code: a static partial OrderLog class with two [LoggerMessage] methods and single-line console output with event IDs 1001 and 1002" class="wp-image-3170" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/loggermessage-source-generator-partial-method-console-output.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/loggermessage-source-generator-partial-method-console-output-278x300.png 278w, https://aspdotnethelp.com/wp-content/uploads/2026/11/loggermessage-source-generator-partial-method-console-output-950x1024.png 950w, https://aspdotnethelp.com/wp-content/uploads/2026/11/loggermessage-source-generator-partial-method-console-output-768x828.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">Event IDs 1001 and 1002 come from the attribute, so each message type is easy to find</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>How does this code work?</strong></p>



<p class="wp-block-paragraph">Each method is <code>static partial</code>, returns <code>void</code> and takes the <code>ILogger</code> as its first parameter. The <code>this</code> makes it an extension method, so you call <code>logger.OrderShipped(...)</code>, the same idea as <a href="https://aspdotnethelp.com/extension-members-in-csharp-14/">extension members in C# 14</a>.</p>



<p class="wp-block-paragraph">The level, event ID and template live in the attribute, and the generator fills in the body at build time. The class has to be <code>partial</code> too; <a href="https://aspdotnethelp.com/partial-class-in-csharp/">partial classes in C#</a> explains how the generated half joins yours.</p>



<p class="wp-block-paragraph"><strong>Pro Tip:</strong> starting with .NET 9, an instance <code>partial</code> class can take the <code>ILogger</code> as a primary constructor parameter, so OrderService could hold these methods itself.</p>



<h2 class="wp-block-heading">Log Scopes and JSON Console Logging in ASP.NET Core</h2>



<p class="wp-block-paragraph">Remember the <code>BeginScope</code> line in OrderService? A scope attaches values to every log line written inside it, so the customer and state ride along without being in each message.</p>



<p class="wp-block-paragraph">The plain console hides scopes. I switched the same orders API to the JSON formatter with scopes on, using environment variables only:</p>



<pre class="wp-block-code"><code>set &quot;Logging__Console__FormatterName=json&quot;
set &quot;Logging__Console__FormatterOptions__IncludeScopes=true&quot;
set &quot;Logging__Console__FormatterOptions__JsonWriterOptions__Indented=true&quot;
dotnet run --no-build</code></pre>



<p class="wp-block-paragraph">Here&#8217;s the entry for order 1042:</p>



<pre class="wp-block-code"><code>{
  &quot;EventId&quot;: 0,
  &quot;LogLevel&quot;: &quot;Information&quot;,
  &quot;Category&quot;: &quot;OrderService&quot;,
  &quot;Message&quot;: &quot;Order 1042 placed for Jenna Morales&quot;,
  &quot;State&quot;: {
    &quot;OrderId&quot;: 1042,
    &quot;Customer&quot;: &quot;Jenna Morales&quot;,
    &quot;{OriginalFormat}&quot;: &quot;Order {OrderId} placed for {Customer}&quot;
  },
  &quot;Scopes&quot;: [
    {
      &quot;Message&quot;: &quot;SpanId:11b6eba551bffca2, TraceId:c9a177f70c1e23858679138dcbc6e35c, ParentId:0000000000000000&quot;,
      &quot;SpanId&quot;: &quot;11b6eba551bffca2&quot;,
      &quot;TraceId&quot;: &quot;c9a177f70c1e23858679138dcbc6e35c&quot;,
      &quot;ParentId&quot;: &quot;0000000000000000&quot;
    },
    {
      &quot;Message&quot;: &quot;ConnectionId:0HNPT7O4O419S&quot;,
      &quot;ConnectionId&quot;: &quot;0HNPT7O4O419S&quot;
    },
    {
      &quot;Message&quot;: &quot;RequestPath:/checkout/1042 RequestId:0HNPT7O4O419S:00000001&quot;,
      &quot;RequestId&quot;: &quot;0HNPT7O4O419S:00000001&quot;,
      &quot;RequestPath&quot;: &quot;/checkout/1042&quot;
    },
    {
      &quot;Message&quot;: &quot;Customer Jenna Morales in TX&quot;,
      &quot;Customer&quot;: &quot;Jenna Morales&quot;,
      &quot;State&quot;: &quot;TX&quot;,
      &quot;{OriginalFormat}&quot;: &quot;Customer {Customer} in {State}&quot;
    }
  ]
}</code></pre>



<p class="wp-block-paragraph"><strong>How does this work?</strong></p>



<p class="wp-block-paragraph">ASP.NET Core opened three scopes before your code ran: the trace and span IDs, the connection, and the <code>RequestId</code> with <code>RequestPath</code>. Your scope came last with <code>Customer</code> and <code>State</code>.</p>



<p class="wp-block-paragraph">That <code>RequestId</code> is gold on a busy server. Filter on it and you get every line from one request, even when many checkouts run at once.</p>



<h2 class="wp-block-heading">Built-in Logging Providers (and Why There&#8217;s No File Provider)</h2>



<p class="wp-block-paragraph"><code>WebApplication.CreateBuilder</code> adds four providers. Here&#8217;s what each one does and where its output goes:</p>



<figure class="wp-block-table"><table><thead><tr><th>Provider</th><th>Writes to</th><th>Good to know</th></tr></thead><tbody><tr><td>Console</td><td>Standard output</td><td>Simple or JSON formatter; gone when the window closes</td></tr><tr><td>Debug</td><td><code>Debug.WriteLine</code></td><td>Only when a debugger is attached</td></tr><tr><td>EventSource</td><td><code>Microsoft-Extensions-Logging</code> event source</td><td>Collect it with dotnet-trace; uses ETW on Windows</td></tr><tr><td>EventLog</td><td>Windows Event Log</td><td>Windows only; defaults to Warning and ignores the default LogLevel</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Microsoft&#8217;s docs say it plainly: ASP.NET Core doesn&#8217;t include a logging provider for writing logs to files. The Azure App Service provider writes text files, but only when the app runs in Azure.</p>



<p class="wp-block-paragraph">So for a file on your own server or VM, you need a third-party provider. Serilog is the one I use, and it plugs into the same <code>ILogger&lt;T&gt;</code> you already wrote, the way <a href="https://aspdotnethelp.com/backgroundservice-vs-ihostedservice/">hosted services in ASP.NET Core</a> plug into the same host.</p>



<h2 class="wp-block-heading">Method 3: Serilog Logging to a Rolling File in ASP.NET Core</h2>



<p class="wp-block-paragraph">Use this when you need logs that survive a restart: on-prem IIS, a Windows service or a Linux VM. The same OrderService.cs file moves over unchanged; only Program.cs and appsettings.json change.</p>



<h3 class="wp-block-heading">Install Serilog.AspNetCore and Serilog.Sinks.File</h3>



<pre class="wp-block-code"><code>dotnet add package Serilog.AspNetCore --version 10.0.0
dotnet add package Serilog.Sinks.File --version 7.0.0</code></pre>



<p class="wp-block-paragraph">Serilog.AspNetCore 10.0.0 already depends on Serilog.Sinks.File 7.0.0, so the second line just pins the version you rely on. Here&#8217;s W12SerilogApi.csproj:</p>



<pre class="wp-block-code"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Serilog.AspNetCore&quot; Version=&quot;10.0.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Serilog.Sinks.File&quot; Version=&quot;7.0.0&quot; /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;</code></pre>



<h3 class="wp-block-heading">Program.cs: bootstrap logger, AddSerilog and UseSerilogRequestLogging</h3>



<p class="wp-block-paragraph">This follows the current Serilog.AspNetCore README, which uses <code>builder.Services.AddSerilog</code> (older posts call <code>builder.Host.UseSerilog</code>):</p>



<pre class="wp-block-code"><code>using System.Globalization;
using Serilog;

CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(&quot;en-US&quot;);   // US dates and 12-hour times in the log
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(outputTemplate: &quot;[{Timestamp:hh:mm:ss tt} {Level:u3}] {Message:lj}{NewLine}{Exception}&quot;)
    .CreateBootstrapLogger();

try
{
    Log.Information(&quot;Starting W12SerilogApi&quot;);
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddSerilog((services, lc) =&gt; lc
        .ReadFrom.Configuration(builder.Configuration)
        .ReadFrom.Services(services));
    builder.Services.AddSingleton&lt;OrderService&gt;();

    var app = builder.Build();
    app.UseSerilogRequestLogging();
    app.MapGet(&quot;/checkout/{id:int}&quot;, (int id, OrderService orders) =&gt; orders.Checkout(id));
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, &quot;W12SerilogApi terminated unexpectedly&quot;);
}
finally
{
    Log.CloseAndFlush();
}</code></pre>



<p class="wp-block-paragraph">Here&#8217;s the console after the same two requests on port 5901:</p>



<pre class="wp-block-code"><code>[07:44:45 AM INF] Starting W12SerilogApi
[07:44:46 AM INF] Now listening on: http://localhost:5901
[07:44:46 AM INF] Application started. Press Ctrl+C to shut down.
[07:44:46 AM INF] Hosting environment: Production
[07:44:46 AM INF] Content root path: C:\DotNetDemo\W12Logging\SerilogApi
[07:44:47 AM INF] Order 1042 placed for Jenna Morales
[07:44:47 AM INF] HTTP GET /checkout/1042 responded 200 in 72.7266 ms
[07:44:48 AM WRN] Order 1043 is over the $5,000 review limit
[07:44:48 AM ERR] Payment failed for order 1043
System.TimeoutException: Payment gateway did not answer in 30 seconds
   at OrderService.Checkout(Int32 id) in C:\DotNetDemo\W12Logging\SerilogApi\OrderService.cs:line 21
[07:44:48 AM ERR] HTTP GET /checkout/1043 responded 500 in 58.6893 ms</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1492" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/serilog-aspnetcore-program-cs-bootstrap-logger-request-logging.png" alt="Serilog.AspNetCore Program.cs in VS Code with CreateBootstrapLogger, AddSerilog and UseSerilogRequestLogging, and the Serilog console output including the HTTP GET responded 500 line" class="wp-image-3172" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/serilog-aspnetcore-program-cs-bootstrap-logger-request-logging.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/serilog-aspnetcore-program-cs-bootstrap-logger-request-logging-278x300.png 278w, https://aspdotnethelp.com/wp-content/uploads/2026/11/serilog-aspnetcore-program-cs-bootstrap-logger-request-logging-950x1024.png 950w, https://aspdotnethelp.com/wp-content/uploads/2026/11/serilog-aspnetcore-program-cs-bootstrap-logger-request-logging-768x828.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">Same OrderService, now on Serilog: one request-logging line per call, and the 500 is logged as an error</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>How does this code work?</strong></p>



<p class="wp-block-paragraph"><code>CreateBootstrapLogger</code> gives you a logger before the host exists, so a crash in startup is logged instead of lost. <code>AddSerilog</code> then replaces it with the full logger built from configuration.</p>



<p class="wp-block-paragraph">The <code>try/catch/finally</code> matters: <code>Log.Fatal</code> records a startup crash and <code>Log.CloseAndFlush</code> writes anything buffered before the process exits. <a href="https://aspdotnethelp.com/try-catch-in-csharp/">Try-catch in C#</a> covers the basics if that pattern is new.</p>



<p class="wp-block-paragraph"><code>UseSerilogRequestLogging</code> adds one summary line per request, like &#8220;HTTP GET /checkout/1043 responded 500&#8221;. Serilog logged the 500 as ERR on its own.</p>



<p class="wp-block-paragraph"><strong>Important:</strong> the culture line is there because this PC isn&#8217;t set to US English. Without it, the hh:mm tt time could print with a lowercase am/pm.</p>



<h3 class="wp-block-heading">Read Serilog settings from the appsettings.json Serilog section</h3>



<p class="wp-block-paragraph"><code>ReadFrom.Configuration</code> reads this section. With Serilog in charge, the old <code>Logging</code> section no longer applies, so I removed it:</p>



<pre class="wp-block-code"><code>{
  &quot;Serilog&quot;: {
    &quot;MinimumLevel&quot;: {
      &quot;Default&quot;: &quot;Information&quot;,
      &quot;Override&quot;: {
        &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;
      }
    },
    &quot;WriteTo&quot;: [
      {
        &quot;Name&quot;: &quot;Console&quot;,
        &quot;Args&quot;: {
          &quot;outputTemplate&quot;: &quot;[{Timestamp:hh:mm:ss tt} {Level:u3}] {Message:lj}{NewLine}{Exception}&quot;
        }
      },
      {
        &quot;Name&quot;: &quot;File&quot;,
        &quot;Args&quot;: {
          &quot;path&quot;: &quot;logs/orders-.log&quot;,
          &quot;rollingInterval&quot;: &quot;Day&quot;,
          &quot;retainedFileCountLimit&quot;: 14,
          &quot;outputTemplate&quot;: &quot;{Timestamp:MM/dd/yyyy hh:mm:ss.fff tt} [{Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}&quot;
        }
      }
    ]
  },
  &quot;AllowedHosts&quot;: &quot;*&quot;,
  &quot;Urls&quot;: &quot;http://localhost:5901&quot;
}</code></pre>



<h3 class="wp-block-heading">The rolling log file</h3>



<p class="wp-block-paragraph">The path <code>logs/orders-.log</code> plus a Day rolling interval makes one file per day with the date added before the dot, and <code>retainedFileCountLimit</code> keeps 14 of them. Here&#8217;s orders-20261108.log after both requests:</p>



<pre class="wp-block-code"><code>11/08/2026 07:35:05.351 AM [INF] Microsoft.Hosting.Lifetime: Now listening on: http://localhost:5901
11/08/2026 07:35:05.384 AM [INF] Microsoft.Hosting.Lifetime: Application started. Press Ctrl+C to shut down.
11/08/2026 07:35:05.386 AM [INF] Microsoft.Hosting.Lifetime: Hosting environment: Production
11/08/2026 07:35:05.388 AM [INF] Microsoft.Hosting.Lifetime: Content root path: C:\DotNetDemo\W12Logging\SerilogApi
11/08/2026 07:35:06.841 AM [INF] OrderService: Order 1042 placed for Jenna Morales
11/08/2026 07:35:06.890 AM [INF] Serilog.AspNetCore.RequestLoggingMiddleware: HTTP GET /checkout/1042 responded 200 in 54.8855 ms
11/08/2026 07:35:07.351 AM [WRN] OrderService: Order 1043 is over the $5,000 review limit
11/08/2026 07:35:07.356 AM [ERR] OrderService: Payment failed for order 1043
System.TimeoutException: Payment gateway did not answer in 30 seconds
   at OrderService.Checkout(Int32 id) in C:\DotNetDemo\W12Logging\SerilogApi\OrderService.cs:line 21
11/08/2026 07:35:07.393 AM [ERR] Serilog.AspNetCore.RequestLoggingMiddleware: HTTP GET /checkout/1043 responded 500 in 41.8156 ms</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1492" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/serilog-rolling-log-file-orders-log-contents-vs-code.png" alt="Serilog rolling log file orders-20261108.log open in VS Code with US-format timestamps, the OrderService warning and the payment timeout stack trace for order 1043" class="wp-image-3173" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/serilog-rolling-log-file-orders-log-contents-vs-code.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/serilog-rolling-log-file-orders-log-contents-vs-code-278x300.png 278w, https://aspdotnethelp.com/wp-content/uploads/2026/11/serilog-rolling-log-file-orders-log-contents-vs-code-950x1024.png 950w, https://aspdotnethelp.com/wp-content/uploads/2026/11/serilog-rolling-log-file-orders-log-contents-vs-code-768x828.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">The file you needed at 2 AM: the warning, the exception and the 500 for order 1043</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>How does this work?</strong></p>



<p class="wp-block-paragraph">Each line uses the file&#8217;s <code>outputTemplate</code>: the US date and 12-hour time, the level in three letters, the <code>SourceContext</code> (Serilog&#8217;s name for the category) and the message. The exception prints on the lines after its entry.</p>



<p class="wp-block-paragraph">Debug lines aren&#8217;t there because the Serilog minimum is Information. To change it, edit <code>Serilog:MinimumLevel</code>, the same way you&#8217;d change any other section you bind with the <a href="https://aspdotnethelp.com/options-pattern-aspnet-core/">options pattern in ASP.NET Core</a>.</p>



<h2 class="wp-block-heading">Serilog vs ASP.NET Core Logging: Which Should You Use?</h2>



<p class="wp-block-paragraph">Keep the built-in logging if you run in Azure or containers and ship logs to a collector. Add Serilog when you need a file or many sinks.</p>



<figure class="wp-block-table"><table><thead><tr><th>Need</th><th>Built-in Microsoft.Extensions.Logging</th><th>Serilog.AspNetCore</th></tr></thead><tbody><tr><td>Log to a file</td><td>No file provider</td><td>Rolling files by day or size</td></tr><tr><td>Packages</td><td>None, ships with ASP.NET Core</td><td>Serilog.AspNetCore 10.0.0</td></tr><tr><td>Structured fields</td><td>Yes, with message templates</td><td>Yes, plus enrichers</td></tr><tr><td>Request summary line</td><td>Several framework lines per request</td><td>One line from UseSerilogRequestLogging</td></tr><tr><td>Startup crash logging</td><td>Not before the host builds</td><td>Bootstrap logger</td></tr><tr><td>Your code</td><td><code>ILogger&lt;T&gt;</code></td><td><code>ILogger&lt;T&gt;</code>, unchanged</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">My pick for a first production API on a VM is Method 1 in your classes plus Method 3 underneath. If you&#8217;re also choosing an API style, <a href="https://aspdotnethelp.com/minimal-api-vs-controllers-aspnet-core/">minimal APIs vs controllers</a> works the same with either logger.</p>



<h2 class="wp-block-heading">Things to Keep in Mind with ASP.NET Core Logging</h2>



<ul class="wp-block-list">
<li><strong>Interpolated messages lose their fields.</strong> Use templates like <code>{OrderId}</code> and raise CA2254 to a warning so the build catches it.</li>

<li><strong>Trace can leak data.</strong> Turn it on for one category in Development only, never as the production default.</li>

<li><strong>EventLog ignores your Default level.</strong> It stays at Warning unless you set Logging:EventLog:LogLevel.</li>

<li><strong>No CloseAndFlush, missing lines.</strong> Keep <code>Log.CloseAndFlush()</code> in the finally block, or the last entries before a crash may never reach the file.</li>

<li><strong>Files grow forever without limits.</strong> Set <code>retainedFileCountLimit</code> and keep the logs folder outside your deployment folder.</li>
</ul>



<h2 class="wp-block-heading">Related ASP.NET Core Tutorials</h2>



<p class="wp-block-paragraph">When your logs look right, these pair well with them:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/asp-net-core-tutorials/">All ASP.NET Core tutorials on AspDotnetHelp</a></li>

<li><a href="https://aspdotnethelp.com/aspnet-core-web-api-crud-ef-core/">Build an ASP.NET Core Web API with EF Core CRUD</a></li>

<li><a href="https://aspdotnethelp.com/httpclient-timeout-csharp/">Set an HttpClient timeout in C#</a></li>

<li><a href="https://aspdotnethelp.com/whats-new-in-dotnet-10/">What&#8217;s new in .NET 10</a></li>
</ul>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-alg120000001" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I write ASP.NET Core logs to a text file?</h3>
<div class="rank-math-answer ">

<p>Add a third-party provider, because ASP.NET Core has none for files. With Serilog, install Serilog.AspNetCore, call <code>builder.Services.AddSerilog()</code> and add a File sink with a path such as <code>logs/orders-.log</code> and a rolling interval.</p>

</div>
</div>
<div id="faq-question-alg120000002" class="rank-math-list-item">
<h3 class="rank-math-question ">What is the default log level in ASP.NET Core?</h3>
<div class="rank-math-answer ">

<p>The template&#8217;s appsettings.json sets Default to Information and Microsoft.AspNetCore to Warning. If no level is configured, logging also defaults to Information, as the <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-10.0" target="_blank" rel="noopener">Microsoft Learn logging docs</a> say.</p>

</div>
</div>
<div id="faq-question-alg120000003" class="rank-math-list-item">
<h3 class="rank-math-question ">Where does ILogger write logs by default?</h3>
<div class="rank-math-answer ">

<p>To the Console, Debug, EventSource and, on Windows, EventLog providers that WebApplication.CreateBuilder adds. None of them writes a file.</p>

</div>
</div>
<div id="faq-question-alg120000004" class="rank-math-list-item">
<h3 class="rank-math-question ">Do I have to change my ILogger code to use Serilog?</h3>
<div class="rank-math-answer ">

<p>No. Classes keep asking for <code>ILogger&lt;T&gt;</code>; Serilog only replaces the provider underneath. Our OrderService.cs ran unchanged in both projects.</p>

</div>
</div>
<div id="faq-question-alg120000005" class="rank-math-list-item">
<h3 class="rank-math-question ">Should I use UseSerilog or AddSerilog?</h3>
<div class="rank-math-answer ">

<p>Use <code>builder.Services.AddSerilog</code>, which is what the <a href="https://github.com/serilog/serilog-aspnetcore" target="_blank" rel="noopener">Serilog.AspNetCore README</a> shows today. <code>builder.Host.UseSerilog</code> is the older host-level form.</p>

</div>
</div>
<div id="faq-question-alg120000006" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I turn off logging for one category?</h3>
<div class="rank-math-answer ">

<p>Set its level to None, for example <code>"Microsoft.AspNetCore": "None"</code> under Logging:LogLevel. None has the value 6, so nothing passes it.</p>

</div>
</div>
</div>
</div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>EF Core Migrations: Add, Remove, Apply and Script (Commands Reference)</title>
		<link>https://aspdotnethelp.com/ef-core-migrations/</link>
		
		<dc:creator><![CDATA[Bijay Kumar]]></dc:creator>
		<pubDate>Sat, 28 Nov 2026 21:20:00 +0000</pubDate>
				<category><![CDATA[ASP.NET Core]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=3093</guid>

					<description><![CDATA[Most EF Core migrations messes I untangle start with dotnet ef migrations remove on a migration that already ran. EF Core 10 refuses: &#8220;has already been applied to the database.&#8221; Deleting the migration file by hand is worse, because nothing fails at all. Roll the database back first, then remove the migration: Below is every ... <a title="EF Core Migrations: Add, Remove, Apply and Script (Commands Reference)" class="read-more" href="https://aspdotnethelp.com/ef-core-migrations/" aria-label="Read more about EF Core Migrations: Add, Remove, Apply and Script (Commands Reference)">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Most <strong>EF Core migrations</strong> messes I untangle start with <code>dotnet ef migrations remove</code> on a migration that already ran. EF Core 10 refuses: &#8220;has already been applied to the database.&#8221; Deleting the migration file by hand is worse, because nothing fails at all.</p>



<p class="wp-block-paragraph">Roll the database back first, then remove the migration:</p>



<pre class="wp-block-code"><code>dotnet ef database update InitialCreate
dotnet ef migrations remove</code></pre>



<p class="wp-block-paragraph">Below is every migrations command I use, each run on .NET 10 with EF Core 10.0.14 against a local SQL Server, plus the safer ways to ship them to production.</p>



<h2 class="wp-block-heading">EF Core Migrations Commands Cheat Sheet</h2>



<p class="wp-block-paragraph">Here&#8217;s the short version. Every command runs from the project folder, and each one builds the project first unless you pass <code>--no-build</code>:</p>



<figure class="wp-block-table"><table><thead><tr><th>Task</th><th>.NET CLI command</th><th>What it does</th></tr></thead><tbody><tr><td>Add a migration</td><td><code>dotnet ef migrations add &lt;Name&gt;</code></td><td>Writes Up/Down code plus a model snapshot</td></tr><tr><td>See applied vs. pending</td><td><code>dotnet ef migrations list</code></td><td>Marks unapplied ones (Pending)</td></tr><tr><td>Apply everything</td><td><code>dotnet ef database update</code></td><td>Runs every pending migration</td></tr><tr><td>Roll back</td><td><code>dotnet ef database update &lt;Name&gt;</code></td><td>Runs Down for every newer migration</td></tr><tr><td>Undo all</td><td><code>dotnet ef database update 0</code></td><td>Reverts every migration</td></tr><tr><td>Remove the last one</td><td><code>dotnet ef migrations remove</code></td><td>Only if it isn&#8217;t applied</td></tr><tr><td>Revert + remove</td><td><code>dotnet ef migrations remove --force</code></td><td>Reverts the database, then deletes the files</td></tr><tr><td>SQL script</td><td><code>dotnet ef migrations script [from] [to]</code></td><td>Prints or saves the SQL</td></tr><tr><td>Safe-to-rerun script</td><td><code>dotnet ef migrations script --idempotent</code></td><td>Checks the history table first</td></tr><tr><td>Bundle</td><td><code>dotnet ef migrations bundle</code></td><td>Builds efbundle.exe</td></tr><tr><td>Forgot a migration?</td><td><code>dotnet ef migrations has-pending-model-changes</code></td><td>Exit code 1 if the model changed</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">This page assumes you already have a DbContext. If you don&#8217;t, my <a href="https://aspdotnethelp.com/ef-core-tutorial/">EF Core tutorial for beginners</a> builds one from scratch, entities and CRUD included.</p>



<h2 class="wp-block-heading">Install dotnet-ef and Microsoft.EntityFrameworkCore.Design</h2>



<p class="wp-block-paragraph">The <code>dotnet ef</code> commands come from a .NET tool, and they also need the Design package in your startup project. I install the tool locally, so its version is pinned in the repo next to the code:</p>



<pre class="wp-block-code"><code>dotnet new console -n W11EfMigrations -o W11EfMigrations
cd W11EfMigrations
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 10.0.14
dotnet add package Microsoft.EntityFrameworkCore.Design --version 10.0.14
dotnet add package System.Security.Cryptography.Pkcs --version 10.0.14
dotnet new tool-manifest
dotnet tool install dotnet-ef --version 10.0.14</code></pre>



<p class="wp-block-paragraph">I added the Pkcs line because the SQL Server provider pulls in an older Pkcs package that <code>dotnet build</code> flags with <code>NU1903</code>. Here are the project file and tool manifest those commands made:</p>



<pre class="wp-block-code"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;OutputType&gt;Exe&lt;/OutputType&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.Design&quot; Version=&quot;10.0.14&quot;&gt;
      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;
      &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;
    &lt;/PackageReference&gt;
    &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.SqlServer&quot; Version=&quot;10.0.14&quot; /&gt;
    &lt;PackageReference Include=&quot;System.Security.Cryptography.Pkcs&quot; Version=&quot;10.0.14&quot; /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;</code></pre>



<pre class="wp-block-code"><code>{
  &quot;version&quot;: 1,
  &quot;isRoot&quot;: true,
  &quot;tools&quot;: {
    &quot;dotnet-ef&quot;: {
      &quot;version&quot;: &quot;10.0.14&quot;,
      &quot;commands&quot;: [
        &quot;dotnet-ef&quot;
      ],
      &quot;rollForward&quot;: false
    }
  }
}</code></pre>



<p class="wp-block-paragraph">A teammate who clones the repo runs <code>dotnet tool restore</code> and gets the same version. Check it with <code>dotnet ef --version</code>:</p>



<pre class="wp-block-code"><code>Entity Framework Core .NET Command-line Tools
10.0.14</code></pre>



<p class="wp-block-paragraph">EF Core 10 needs .NET 10, so <a href="https://aspdotnethelp.com/check-dotnet-version/">check your .NET SDK version</a> if the packages refuse to install. A project still on .NET 8 needs the <a href="https://aspdotnethelp.com/upgrade-dotnet-8-to-dotnet-10/">.NET 8 to .NET 10 upgrade</a> first.</p>



<h2 class="wp-block-heading">The Sample EF Core Model Behind Every Command</h2>



<p class="wp-block-paragraph">Every command below runs against the same small catalog for Trailhead Outfitters, a made-up outdoor gear store in Boise, Idaho. Version one of the entity has three properties:</p>



<pre class="wp-block-code"><code>namespace W11EfMigrations;

public class Product
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public decimal Price { get; set; }
}</code></pre>



<p class="wp-block-paragraph">The context points at a local SQL Server database named <code>W11EfMigrations</code>, with Windows authentication:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;

namespace W11EfMigrations;

public class StoreDb : DbContext
{
    public DbSet&lt;Product&gt; Products =&gt; Set&lt;Product&gt;();

    protected override void OnConfiguring(DbContextOptionsBuilder options) =&gt;
        options.UseSqlServer(&quot;Server=.;Database=W11EfMigrations;Trusted_Connection=True;TrustServerCertificate=True&quot;);

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&lt;Product&gt;().Property(p =&gt; p.Name).HasMaxLength(80);
        modelBuilder.Entity&lt;Product&gt;().Property(p =&gt; p.Price).HasPrecision(10, 2);
    }
}</code></pre>



<p class="wp-block-paragraph"><strong>Note:</strong> a hard-coded connection string keeps the demo short. In a real app, read it from configuration (my <a href="https://aspdotnethelp.com/options-pattern-aspnet-core/">options pattern guide</a> covers that side) and register the context with <code>AddDbContext</code>.</p>



<h2 class="wp-block-heading">Add a Migration with dotnet ef migrations add</h2>



<p class="wp-block-paragraph">A migration compares your model with the last snapshot and writes C# that changes the schema. Name it like a commit message:</p>



<pre class="wp-block-code"><code>dotnet ef migrations add InitialCreate</code></pre>



<pre class="wp-block-code"><code>Build started...
Build succeeded.
Done. To undo this action, use &#x27;ef migrations remove&#x27;</code></pre>



<p class="wp-block-paragraph">It created three files in a <code>Migrations</code> folder: the migration, a designer file with metadata, and the model snapshot that the next <code>migrations add</code> compares against:</p>



<pre class="wp-block-code"><code>20261107200540_InitialCreate.Designer.cs
20261107200540_InitialCreate.cs
StoreDbModelSnapshot.cs</code></pre>



<p class="wp-block-paragraph">The 14-digit prefix is a UTC timestamp, so files sort in the order they were created. Use <code>--output-dir</code> (<code>-o</code>) for a different folder and <code>--namespace</code> (<code>-n</code>) for a different namespace.</p>



<h3 class="wp-block-heading">See which migrations are applied with migrations list</h3>



<p class="wp-block-paragraph">Run <code>dotnet ef migrations list</code>. It connects to the database and adds <code>(Pending)</code> after every migration that hasn&#8217;t run yet. Right after the add, that&#8217;s InitialCreate:</p>



<pre class="wp-block-code"><code>20261107200540_InitialCreate (Pending)</code></pre>



<p class="wp-block-paragraph">Pass <code>--no-connect</code> to list the migrations in the project without touching the database. In code, <code>GetAppliedMigrationsAsync()</code> and <code>GetPendingMigrationsAsync()</code> give you the same two lists.</p>



<h2 class="wp-block-heading">Apply Migrations with dotnet ef database update</h2>



<p class="wp-block-paragraph"><code>database update</code> creates the database if it&#8217;s missing and applies every pending migration:</p>



<pre class="wp-block-code"><code>Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
Applying migration &#x27;20261107200540_InitialCreate&#x27;.
Done.</code></pre>



<p class="wp-block-paragraph">The &#8220;exclusive lock&#8221; line comes from EF Core 9 and later. Two deployments can&#8217;t apply migrations to the same database at once anymore, which is one of the changes I listed in <a href="https://aspdotnethelp.com/whats-new-in-dotnet-10/">what is new in .NET 10</a>.</p>



<p class="wp-block-paragraph">Now a real model change. The store wants a category on each product, so <code>Product</code> gets an optional <code>Category</code>, nullable thanks to <a href="https://aspdotnethelp.com/csharp-nullable-reference-types/">nullable reference types</a>:</p>



<pre class="wp-block-code"><code>using System.ComponentModel.DataAnnotations;

namespace W11EfMigrations;

public class Product
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public decimal Price { get; set; }

    [MaxLength(40)]
    public string? Category { get; set; }
}</code></pre>



<pre class="wp-block-code"><code>dotnet ef migrations add AddProductCategory
dotnet ef database update</code></pre>



<p class="wp-block-paragraph">Always open the generated file before you apply it. This one is exactly what I wanted, a nullable nvarchar(40) column, with a Down method that drops it again:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace W11EfMigrations.Migrations
{
    /// &lt;inheritdoc /&gt;
    public partial class AddProductCategory : Migration
    {
        /// &lt;inheritdoc /&gt;
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn&lt;string&gt;(
                name: &quot;Category&quot;,
                table: &quot;Products&quot;,
                type: &quot;nvarchar(40)&quot;,
                maxLength: 40,
                nullable: true);
        }

        /// &lt;inheritdoc /&gt;
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: &quot;Category&quot;,
                table: &quot;Products&quot;);
        }
    }
}</code></pre>



<pre class="wp-block-code"><code>Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
Applying migration &#x27;20261107200636_AddProductCategory&#x27;.
Done.</code></pre>



<p class="wp-block-paragraph"><strong>Important:</strong> EF Core can&#8217;t tell a rename from a drop plus an add. If you rename a property, change the generated <code>DropColumn</code>/<code>AddColumn</code> pair to <code>RenameColumn</code>, or the data in that column is gone.</p>



<h2 class="wp-block-heading">How Do You Remove a Migration in EF Core?</h2>



<p class="wp-block-paragraph">If the migration isn&#8217;t applied yet, <code>dotnet ef migrations remove</code> deletes the newest migration and rolls the snapshot back. Once it&#8217;s applied, you get the error from the top of this page:</p>



<pre class="wp-block-code"><code>dotnet ef migrations remove</code></pre>



<pre class="wp-block-code"><code>The migration &#x27;20261107200636_AddProductCategory&#x27; has already been applied to the database. Revert it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration instead.</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1092" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrations-remove-error-migration-already-applied.png" alt="VS Code running dotnet ef migrations remove on an applied EF Core migration: the AddPriceSummaryView migration is open and the terminal says the migration has already been applied to the database" class="wp-image-3131" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrations-remove-error-migration-already-applied.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrations-remove-error-migration-already-applied-300x237.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrations-remove-error-migration-already-applied-1024x808.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrations-remove-error-migration-already-applied-768x606.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">The tools won&#8217;t remove a migration that&#8217;s already in the database</figcaption></figure>
</div>


<p class="wp-block-paragraph">On your own dev database, you have two fixes. Update to the previous migration and then remove, as in the intro, or let <code>--force</code> do both steps:</p>



<pre class="wp-block-code"><code>dotnet ef migrations remove --force</code></pre>



<pre class="wp-block-code"><code>Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
Reverting migration &#x27;20261107200636_AddProductCategory&#x27;.
Removing migration &#x27;20261107200636_AddProductCategory&#x27;.
Reverting the model snapshot.
Done.</code></pre>



<p class="wp-block-paragraph">That reverted the database and deleted the files. A quick look at the table confirmed the <code>Category</code> column was gone again:</p>



<pre class="wp-block-code"><code>name
----
Id
Name
Price</code></pre>



<p class="wp-block-paragraph"><strong>Important:</strong> never remove a migration that already ran on a shared, test or production database. Add a new corrective migration instead, so every database can still move forward from where it is.</p>



<p class="wp-block-paragraph">For the rest of this page, I added AddProductCategory back and applied it, so it has a new ID: <code>20261107200736_AddProductCategory</code>.</p>



<h2 class="wp-block-heading">What Happens If You Delete a Migration File by Hand?</h2>



<p class="wp-block-paragraph">Nothing warns you, and that&#8217;s the problem. I deleted the AddProductCategory migration and its designer file while the migration was applied. The list just stopped showing it:</p>



<pre class="wp-block-code"><code>20261107200540_InitialCreate</code></pre>



<p class="wp-block-paragraph"><code>has-pending-model-changes</code> also said everything was fine, because the snapshot still contains <code>Category</code>:</p>



<pre class="wp-block-code"><code>No changes have been made to the model since the last migration.</code></pre>



<p class="wp-block-paragraph">Then I tried to roll back to InitialCreate. EF Core had no Down code for the missing migration, so it did nothing:</p>



<pre class="wp-block-code"><code>Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
No migrations were applied. The database is already up to date.
Done.</code></pre>



<p class="wp-block-paragraph">The <code>Category</code> column was still there in SQL Server:</p>



<pre class="wp-block-code"><code>name
----
Id
Name
Price
Category</code></pre>



<p class="wp-block-paragraph">The fix is to restore the files from source control. If they&#8217;re truly lost, add a migration that matches what&#8217;s in the database, the way Microsoft&#8217;s squashing steps do. Either way, let <code>migrations remove</code> delete migrations, not File Explorer.</p>



<h2 class="wp-block-heading">Roll Back a Migration with database update and a Migration Name</h2>



<p class="wp-block-paragraph">There&#8217;s no separate rollback command. <code>database update</code> takes the migration you want the database to end at, and runs the Down method of everything newer. I had three applied migrations at this point:</p>



<pre class="wp-block-code"><code>dotnet ef database update InitialCreate</code></pre>



<pre class="wp-block-code"><code>Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
Reverting migration &#x27;20261107200828_AddPriceSummaryView&#x27;.
Reverting migration &#x27;20261107200736_AddProductCategory&#x27;.
Done.</code></pre>



<p class="wp-block-paragraph">Both newer migrations went back in reverse order, and the list now shows them as pending again:</p>



<pre class="wp-block-code"><code>20261107200540_InitialCreate
20261107200736_AddProductCategory (Pending)
20261107200828_AddPriceSummaryView (Pending)</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1092" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/dotnet-ef-migrations-list-applied-and-pending.png" alt="VS Code with Product.cs open: dotnet ef database update AddProductCategory reverts the AddPriceSummaryView migration and dotnet ef migrations list shows it as Pending" class="wp-image-3126" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/dotnet-ef-migrations-list-applied-and-pending.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/dotnet-ef-migrations-list-applied-and-pending-300x237.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/dotnet-ef-migrations-list-applied-and-pending-1024x808.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/dotnet-ef-migrations-list-applied-and-pending-768x606.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">Updating to AddProductCategory reverted the newest migration; the list marks it (Pending)</figcaption></figure>
</div>


<p class="wp-block-paragraph">The special target <code>0</code> means before the first migration, so it reverts everything:</p>



<pre class="wp-block-code"><code>dotnet ef database update 0</code></pre>



<pre class="wp-block-code"><code>Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
Reverting migration &#x27;20261107200540_InitialCreate&#x27;.
Done.</code></pre>



<p class="wp-block-paragraph"><strong>Note:</strong> a rollback runs real Down code. Down methods that drop columns lose that data, so test them on a copy before you count on them in production.</p>



<h2 class="wp-block-heading">Catch a Forgotten Migration with has-pending-model-changes</h2>



<p class="wp-block-paragraph">This command, added in EF Core 8, compares the model with the last snapshot. Right after I added <code>Category</code> to the class, and before I added its migration, it said:</p>



<pre class="wp-block-code"><code>dotnet ef migrations has-pending-model-changes</code></pre>



<pre class="wp-block-code"><code>Changes have been made to the model since the last migration. Add a new migration.</code></pre>



<p class="wp-block-paragraph">It also exited with code 1, and with 0 once the migration existed. That makes it a one-line CI gate that fails the build when someone changes an entity and forgets <code>migrations add</code>.</p>



<p class="wp-block-paragraph">In tests, call <code>context.Database.HasPendingModelChanges()</code> and assert it&#8217;s false. I&#8217;d put that in the same project as the rest of your <a href="https://aspdotnethelp.com/xunit-unit-testing-csharp/">xUnit tests</a>.</p>



<h2 class="wp-block-heading">Run Custom SQL in a Migration with migrationBuilder.Sql</h2>



<p class="wp-block-paragraph">Migrations can manage things EF Core doesn&#8217;t model, like views, stored procedures and triggers. Add a migration without changing the model, and you get a class with empty <code>Up</code> and <code>Down</code> methods to fill in:</p>



<pre class="wp-block-code"><code>dotnet ef migrations add AddPriceSummaryView</code></pre>



<p class="wp-block-paragraph">My first version put a plain <code>CREATE VIEW</code> inside <code>migrationBuilder.Sql</code>. That version is fine with <code>database update</code>, but it breaks the idempotent script in the next section, so here&#8217;s the version I kept, with the statement wrapped in <code>EXEC</code>:</p>



<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace W11EfMigrations.Migrations
{
    /// &lt;inheritdoc /&gt;
    public partial class AddPriceSummaryView : Migration
    {
        /// &lt;inheritdoc /&gt;
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(&quot;&quot;&quot;
                EXEC(&#x27;CREATE VIEW dbo.CategoryPriceSummary AS
                SELECT Category, COUNT(*) AS Products, AVG(Price) AS AvgPrice
                FROM dbo.Products
                GROUP BY Category&#x27;);
                &quot;&quot;&quot;);
        }

        /// &lt;inheritdoc /&gt;
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(&quot;DROP VIEW dbo.CategoryPriceSummary;&quot;);
        }
    }
}</code></pre>



<p class="wp-block-paragraph">The Down method drops the view, so a rollback stays clean. The view groups products by category, the same idea as <a href="https://aspdotnethelp.com/linq-groupby-in-csharp/">LINQ GroupBy in C#</a>, just running in SQL Server.</p>



<h2 class="wp-block-heading">Generate SQL Scripts with dotnet ef migrations script</h2>



<p class="wp-block-paragraph">Scripts are what you hand to a DBA or a release pipeline that wants to review SQL first. With a from and a to, you get just the steps in between. The from is the last migration already applied:</p>



<pre class="wp-block-code"><code>dotnet ef migrations script InitialCreate AddProductCategory</code></pre>



<pre class="wp-block-code"><code>BEGIN TRANSACTION;
ALTER TABLE [Products] ADD [Category] nvarchar(40) NULL;

INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
VALUES (N&#x27;20261107200736_AddProductCategory&#x27;, N&#x27;10.0.14&#x27;);

COMMIT;
GO</code></pre>



<p class="wp-block-paragraph">No arguments means from <code>0</code> to the latest migration. Swap from and to to get a rollback script. Add <code>--output</code> to save a file instead of printing to the console:</p>



<pre class="wp-block-code"><code>dotnet ef migrations script --output artifacts/migrate.sql
dotnet ef migrations script --idempotent --output artifacts/migrate-idempotent.sql</code></pre>



<p class="wp-block-paragraph">A plain script only works on a database at the exact from migration. An <code>--idempotent</code> script wraps each migration in an <code>IF NOT EXISTS</code> check against the history table, so you can run it against any version of the database.</p>



<h3 class="wp-block-heading">Why CREATE VIEW broke the idempotent script</h3>



<p class="wp-block-paragraph">Here&#8217;s what that check did to my first view migration:</p>



<pre class="wp-block-code"><code>IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N&#x27;20261107200540_InitialCreate&#x27;
)
BEGIN
    CREATE TABLE [Products] (
        [Id] int NOT NULL IDENTITY,
        [Name] nvarchar(80) NOT NULL,
        [Price] decimal(10,2) NOT NULL,
        CONSTRAINT [PK_Products] PRIMARY KEY ([Id])
    );
END;

IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N&#x27;20261107200540_InitialCreate&#x27;
)
BEGIN
    INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
    VALUES (N&#x27;20261107200540_InitialCreate&#x27;, N&#x27;10.0.14&#x27;);
END;

COMMIT;
GO

BEGIN TRANSACTION;
IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N&#x27;20261107200736_AddProductCategory&#x27;
)
BEGIN
    ALTER TABLE [Products] ADD [Category] nvarchar(40) NULL;
END;

IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N&#x27;20261107200736_AddProductCategory&#x27;
)
BEGIN
    INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
    VALUES (N&#x27;20261107200736_AddProductCategory&#x27;, N&#x27;10.0.14&#x27;);
END;

COMMIT;
GO

BEGIN TRANSACTION;
IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N&#x27;20261107200828_AddPriceSummaryView&#x27;
)
BEGIN
    CREATE VIEW dbo.CategoryPriceSummary AS
    SELECT Category, COUNT(*) AS Products, AVG(Price) AS AvgPrice
    FROM dbo.Products
    GROUP BY Category;
END;</code></pre>



<p class="wp-block-paragraph">SQL Server wants <code>CREATE VIEW</code> to be the first statement in its batch, and here it sits inside <code>BEGIN</code>. Running the script with sqlcmd on an empty <code>W11EfMigrations</code> database failed:</p>



<pre class="wp-block-code"><code>sqlcmd -S . -E -d W11EfMigrations -b -i artifacts\migrate-idempotent.sql</code></pre>



<pre class="wp-block-code"><code>Incorrect syntax near the keyword &#x27;VIEW&#x27;.</code></pre>



<p class="wp-block-paragraph">That&#8217;s error Msg 156, and it hit after the script had already applied the first 2 migrations. A half-applied deployment script is exactly what you don&#8217;t want.</p>



<p class="wp-block-paragraph">With the <code>EXEC</code> version, the same block becomes legal T-SQL:</p>



<pre class="wp-block-code"><code>BEGIN TRANSACTION;
IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N&#x27;20261107200540_InitialCreate&#x27;
)
BEGIN
    CREATE TABLE [Products] (
        [Id] int NOT NULL IDENTITY,
        [Name] nvarchar(80) NOT NULL,
        [Price] decimal(10,2) NOT NULL,
        CONSTRAINT [PK_Products] PRIMARY KEY ([Id])
    );
END;

IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N&#x27;20261107200540_InitialCreate&#x27;
)
BEGIN
    INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
    VALUES (N&#x27;20261107200540_InitialCreate&#x27;, N&#x27;10.0.14&#x27;);
END;

COMMIT;
GO

BEGIN TRANSACTION;
IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N&#x27;20261107200736_AddProductCategory&#x27;
)
BEGIN
    ALTER TABLE [Products] ADD [Category] nvarchar(40) NULL;
END;

IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N&#x27;20261107200736_AddProductCategory&#x27;
)
BEGIN
    INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
    VALUES (N&#x27;20261107200736_AddProductCategory&#x27;, N&#x27;10.0.14&#x27;);
END;

COMMIT;
GO

BEGIN TRANSACTION;
IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N&#x27;20261107200828_AddPriceSummaryView&#x27;
)
BEGIN
    EXEC(&#x27;CREATE VIEW dbo.CategoryPriceSummary AS
    SELECT Category, COUNT(*) AS Products, AVG(Price) AS AvgPrice
    FROM dbo.Products
    GROUP BY Category&#x27;);
END;</code></pre>



<p class="wp-block-paragraph">This time the script ran with no errors. Running it a second time changed nothing, because every block checks the history table first. Here&#8217;s the history table afterward:</p>



<pre class="wp-block-code"><code>MigrationId ProductVersion
----------- --------------
20261107200540_InitialCreate 10.0.14
20261107200736_AddProductCategory 10.0.14
20261107200828_AddPriceSummaryView 10.0.14</code></pre>



<p class="wp-block-paragraph"><strong>Note:</strong> a script doesn&#8217;t create the database. Provision it first, as I did with <code>CREATE DATABASE</code>, and SQLite can&#8217;t generate idempotent scripts at all.</p>



<h2 class="wp-block-heading">Build and Run a Migration Bundle (efbundle.exe)</h2>



<p class="wp-block-paragraph">A bundle is a single executable that applies your migrations. Microsoft recommends it for automated deployments: the server doesn&#8217;t need the .NET SDK, the EF tool or your source code.</p>



<pre class="wp-block-code"><code>dotnet ef migrations bundle --force --output artifacts/efbundle.exe</code></pre>



<pre class="wp-block-code"><code>Building bundle...
Done. Migrations Bundle: C:\DotNetDemo\W11EfMigrations\artifacts\efbundle.exe</code></pre>



<p class="wp-block-paragraph">Mine came out at about 45 MB. I dropped the database and ran it, and it applied all three migrations, including the view:</p>



<pre class="wp-block-code"><code>Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
Applying migration &#x27;20261107200540_InitialCreate&#x27;.
Applying migration &#x27;20261107200736_AddProductCategory&#x27;.
Applying migration &#x27;20261107200828_AddPriceSummaryView&#x27;.
Done.</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1092" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrations-bundle-efbundle-exe-apply.png" alt="VS Code running artifacts\efbundle.exe: the EF Core migration bundle acquires the migration lock and applies InitialCreate, AddProductCategory and AddPriceSummaryView to SQL Server" class="wp-image-3129" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrations-bundle-efbundle-exe-apply.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrations-bundle-efbundle-exe-apply-300x237.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrations-bundle-efbundle-exe-apply-1024x808.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrations-bundle-efbundle-exe-apply-768x606.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">efbundle.exe applied all three migrations to an empty database</figcaption></figure>
</div>


<p class="wp-block-paragraph">A second run is safe, which is exactly what a deployment pipeline needs:</p>



<pre class="wp-block-code"><code>Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
No migrations were applied. The database is already up to date.
Done.</code></pre>



<p class="wp-block-paragraph">By default, the bundle uses the connection string from <code>OnConfiguring</code> or <code>AddDbContext</code>. In a pipeline, pass <code>--connection</code> from your secret store, and set <code>ASPNETCORE_ENVIRONMENT</code> so it reads the <a href="https://aspdotnethelp.com/appsettings-per-environment-aspnet-core/">right appsettings file per environment</a>.</p>



<p class="wp-block-paragraph">For a Linux build agent or container, add <code>--self-contained --target-runtime linux-x64</code>. A bundle also takes a target migration, so <code>efbundle.exe 0</code> reverts everything.</p>



<h2 class="wp-block-heading">Should You Apply Migrations on Startup with MigrateAsync?</h2>



<p class="wp-block-paragraph">You can apply migrations from the app itself. Here&#8217;s the final <code>Program.cs</code> of my demo: it migrates, then seeds four products if the table is empty:</p>



<pre class="wp-block-code"><code>using System.Globalization;
using Microsoft.EntityFrameworkCore;
using W11EfMigrations;

CultureInfo.CurrentCulture = new CultureInfo(&quot;en-US&quot;);
await using var db = new StoreDb();

await db.Database.MigrateAsync();   // apply pending migrations at startup
var applied = await db.Database.GetAppliedMigrationsAsync();
Console.WriteLine($&quot;Applied migrations: {applied.Count()}&quot;);

if (!await db.Products.AnyAsync())
{
    db.Products.AddRange(
        new Product { Name = &quot;Trail Daypack 28L&quot;, Price = 89.99m, Category = &quot;Packs&quot; },
        new Product { Name = &quot;Ridgeline 2P Tent&quot;, Price = 249.00m, Category = &quot;Shelter&quot; },
        new Product { Name = &quot;Summit Trekking Poles&quot;, Price = 64.50m, Category = &quot;Hiking&quot; },
        new Product { Name = &quot;Canyon Hydration Pack&quot;, Price = 74.95m, Category = &quot;Packs&quot; });
    await db.SaveChangesAsync();
}
Console.WriteLine($&quot;Products: {await db.Products.CountAsync()}, total {await db.Products.SumAsync(p =&gt; p.Price):C}&quot;);</code></pre>



<p class="wp-block-paragraph">The first run against an empty database created everything, and the <a href="https://aspdotnethelp.com/async-await-in-csharp/">awaited</a> calls printed:</p>



<pre class="wp-block-code"><code>Applied migrations: 3
Products: 4, total $478.44</code></pre>



<p class="wp-block-paragraph">It&#8217;s handy for demos, local tools and small single-instance apps. For production, Microsoft&#8217;s applying-migrations guide prefers a bundle or a reviewed script, and lists these tradeoffs:</p>



<ul class="wp-block-list">
<li>The app&#8217;s database login needs schema-change rights, which you&#8217;d normally keep away from the app.</li>

<li>The SQL runs with no chance to review it first.</li>

<li>Rolling back an applied migration is harder than with a script or bundle.</li>

<li>Other apps using the database while it migrates can break. Before EF Core 9, two instances could also migrate at once.</li>
</ul>



<p class="wp-block-paragraph">In ASP.NET Core, resolve the context from a scope created from <code>app.Services</code>, because a DbContext is scoped. My <a href="https://aspdotnethelp.com/dependency-injection-lifetimes-aspnet-core/">DI lifetimes guide</a> explains why you can&#8217;t take it from the root provider.</p>



<h3 class="wp-block-heading">PendingModelChangesWarning: why Migrate() throws in EF Core 9 and 10</h3>



<p class="wp-block-paragraph">Starting with EF Core 9, <code>Migrate()</code> and <code>MigrateAsync()</code> throw if the model has changes with no migration. I added a <code>Stock</code> property and ran the app without a new migration:</p>



<pre class="wp-block-code"><code>using System.ComponentModel.DataAnnotations;

namespace W11EfMigrations;

public class Product
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public decimal Price { get; set; }

    [MaxLength(40)]
    public string? Category { get; set; }

    public int Stock { get; set; }   // new, no migration yet
}</code></pre>



<pre class="wp-block-code"><code>Unhandled exception. System.InvalidOperationException: An error was generated for warning &#x27;Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning&#x27;: The model for context &#x27;StoreDb&#x27; has pending changes. Add a new migration before updating the database. See https://aka.ms/efcore-docs-pending-changes. This exception can be suppressed or logged by passing event ID &#x27;RelationalEventId.PendingModelChangesWarning&#x27; to the &#x27;ConfigureWarnings&#x27; method in &#x27;DbContext.OnConfiguring&#x27; or &#x27;AddDbContext&#x27;.</code></pre>



<p class="wp-block-paragraph">In the screenshot, I piped the run through <code>findstr /v /c:"   at "</code> to hide the stack trace and keep the message on screen:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1092" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrate-pendingmodelchangeswarning-exception.png" alt="VS Code running the EF Core app after adding a Stock property without a migration: MigrateAsync throws InvalidOperationException for PendingModelChangesWarning, the model for context StoreDb has pending changes" class="wp-image-3127" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrate-pendingmodelchangeswarning-exception.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrate-pendingmodelchangeswarning-exception-300x237.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrate-pendingmodelchangeswarning-exception-1024x808.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrate-pendingmodelchangeswarning-exception-768x606.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">MigrateAsync refuses to run when the model has changes with no migration</figcaption></figure>
</div>


<p class="wp-block-paragraph">The fix is to add the migration. You can suppress it with <code>ConfigureWarnings(w =&gt; w.Ignore(RelationalEventId.PendingModelChangesWarning))</code>, but Microsoft doesn&#8217;t recommend that in production. Running <code>has-pending-model-changes</code> in CI catches it before deployment.</p>



<h2 class="wp-block-heading">What Is the __EFMigrationsHistory Table?</h2>



<p class="wp-block-paragraph">It&#8217;s how EF Core knows what&#8217;s applied: one row per migration, with the EF Core version that applied it. Same app, then a query straight against SQL Server:</p>



<pre class="wp-block-code"><code>sqlcmd -S . -E -d W11EfMigrations -W -Q &quot;SET NOCOUNT ON; SELECT MigrationId, ProductVersion FROM __EFMigrationsHistory ORDER BY MigrationId&quot;</code></pre>



<pre class="wp-block-code"><code>MigrationId ProductVersion
----------- --------------
20261107200540_InitialCreate 10.0.14
20261107200736_AddProductCategory 10.0.14
20261107200828_AddPriceSummaryView 10.0.14</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1092" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrateasync-startup-efmigrationshistory-table.png" alt="VS Code with Program.cs calling MigrateAsync: dotnet run prints Applied migrations: 3, then sqlcmd lists the three rows of the EF Core __EFMigrationsHistory table with ProductVersion 10.0.14" class="wp-image-3128" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrateasync-startup-efmigrationshistory-table.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrateasync-startup-efmigrationshistory-table-300x237.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrateasync-startup-efmigrationshistory-table-1024x808.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/ef-core-migrateasync-startup-efmigrationshistory-table-768x606.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">dotnet run, then the three rows EF Core wrote to __EFMigrationsHistory</figcaption></figure>
</div>


<p class="wp-block-paragraph">The view from the custom SQL migration works too, averaging the four products by category:</p>



<pre class="wp-block-code"><code>Category Products AvgPrice
-------- -------- --------
Hiking 1 64.500000
Packs 2 82.470000
Shelter 1 249.000000</code></pre>



<p class="wp-block-paragraph">From C#, <code>GetAppliedMigrationsAsync()</code> returns the same IDs as a sequence, so you can count or filter them with <a href="https://aspdotnethelp.com/linq-in-csharp/">LINQ</a>, as my Program.cs does with <code>Count()</code>.</p>



<p class="wp-block-paragraph">Treat the table as EF Core&#8217;s. Editing its rows by hand has the same effect as the deleted-file mistake earlier: EF Core trusts it and skips or repeats migrations.</p>



<h2 class="wp-block-heading">Package Manager Console Equivalents for EF Core Migrations</h2>



<p class="wp-block-paragraph">In Visual Studio&#8217;s Package Manager Console, the same tools take PowerShell names. The Microsoft.EntityFrameworkCore.Tools package provides them:</p>



<figure class="wp-block-table"><table><thead><tr><th>dotnet ef (CLI)</th><th>Package Manager Console</th></tr></thead><tbody><tr><td><code>migrations add InitialCreate</code></td><td><code>Add-Migration InitialCreate</code></td></tr><tr><td><code>migrations remove</code></td><td><code>Remove-Migration</code></td></tr><tr><td><code>migrations remove --force</code></td><td><code>Remove-Migration -Force</code></td></tr><tr><td><code>migrations list</code></td><td><code>Get-Migration</code></td></tr><tr><td><code>database update InitialCreate</code></td><td><code>Update-Database InitialCreate</code></td></tr><tr><td><code>migrations script --idempotent</code></td><td><code>Script-Migration -Idempotent</code></td></tr><tr><td><code>migrations bundle</code></td><td><code>Bundle-Migration</code></td></tr></tbody></table></figure>



<p class="wp-block-paragraph">The behavior is identical. I stick to the CLI because the same commands run on a Mac, in a build pipeline and in a <a href="https://aspdotnethelp.com/create-a-console-application-in-visual-studio-code/">console app in VS Code</a>.</p>



<h2 class="wp-block-heading">EF Core Migrations with Multiple DbContexts or a Separate Project</h2>



<p class="wp-block-paragraph">With more than one DbContext in a project, every command needs <code>--context</code> (<code>-c</code>). Give each context its own folder, so their snapshots don&#8217;t collide:</p>



<pre class="wp-block-code"><code>dotnet ef migrations add InitialCreate --context StoreDb --output-dir Migrations/Store
dotnet ef database update --context StoreDb</code></pre>



<p class="wp-block-paragraph">When the DbContext lives in a class library and a web app or <a href="https://aspdotnethelp.com/dependency-injection-console-app-csharp/">console app with dependency injection</a> starts it, point the tools at both projects:</p>



<pre class="wp-block-code"><code>dotnet ef migrations add AddProductCategory --project src/Store.Data --startup-project src/Store.Api</code></pre>



<p class="wp-block-paragraph"><code>--project</code> is where the files are written, and <code>--startup-project</code> is the one the tools build and run to read your configuration. If that pairing gets messy, the <a href="https://aspdotnethelp.com/aspnet-core-web-api-crud-ef-core/">ASP.NET Core Web API CRUD with EF Core</a> post shows the single-project setup most APIs start with.</p>



<p class="wp-block-paragraph">A few more EF Core and ASP.NET Core pages worth bookmarking:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/asp-net-core-tutorials/">Every ASP.NET Core tutorial on the site</a></li>

<li><a href="https://aspdotnethelp.com/csharp-tutorials/">All C# tutorials, beginner to advanced</a></li>

<li><a href="https://aspdotnethelp.com/dotnet-versions/">Which .NET version supports which EF Core</a></li>

<li><a href="https://aspdotnethelp.com/learn-csharp/">The learn C# roadmap</a></li>
</ul>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-efm110000001" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I add a migration in EF Core?</h3>
<div class="rank-math-answer ">

<p>Run <code>dotnet ef migrations add &lt;Name&gt;</code> in the project folder, review the generated file, then run <code>dotnet ef database update</code>. In Visual Studio&#8217;s Package Manager Console, use <code>Add-Migration &lt;Name&gt;</code>.</p>

</div>
</div>
<div id="faq-question-efm110000002" class="rank-math-list-item">
<h3 class="rank-math-question ">How do I undo the last EF Core migration?</h3>
<div class="rank-math-answer ">

<p>If it isn&#8217;t applied, run <code>dotnet ef migrations remove</code>. If it is, run <code>dotnet ef database update &lt;PreviousMigration&gt;</code> first, or use <code>dotnet ef migrations remove --force</code>, which reverts the database and deletes the files.</p>

</div>
</div>
<div id="faq-question-efm110000003" class="rank-math-list-item">
<h3 class="rank-math-question ">Can I delete EF Core migration files manually?</h3>
<div class="rank-math-answer ">

<p>Not safely. The snapshot and the history table still remember the migration, so EF Core can&#8217;t roll it back and won&#8217;t warn you. Remove migrations with the tools, and restore deleted files from source control.</p>

</div>
</div>
<div id="faq-question-efm110000004" class="rank-math-list-item">
<h3 class="rank-math-question ">Should I run Migrate() when my app starts?</h3>
<div class="rank-math-answer ">

<p>Only for small single-instance apps you control. For production, Microsoft recommends a migration bundle or an idempotent SQL script. See <a href="https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying" target="_blank" rel="noopener">Applying Migrations on Microsoft Learn</a>.</p>

</div>
</div>
<div id="faq-question-efm110000005" class="rank-math-list-item">
<h3 class="rank-math-question ">Why does Migrate throw PendingModelChangesWarning?</h3>
<div class="rank-math-answer ">

<p>Since EF Core 9, Migrate and MigrateAsync throw when the model changed but no migration captures it. Add the missing migration, and run has-pending-model-changes in CI so it doesn&#8217;t reach production.</p>

</div>
</div>
<div id="faq-question-efm110000006" class="rank-math-list-item">
<h3 class="rank-math-question ">What does dotnet ef database update 0 do?</h3>
<div class="rank-math-answer ">

<p>It reverts every migration by running each Down method, newest first. The history rows go with them. The full option list is in the <a href="https://learn.microsoft.com/en-us/ef/core/cli/dotnet" target="_blank" rel="noopener">EF Core .NET CLI reference</a>.</p>

</div>
</div>
</div>
</div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Blazor Server vs WebAssembly vs Auto: Which Should You Choose?</title>
		<link>https://aspdotnethelp.com/blazor-server-vs-webassembly/</link>
		
		<dc:creator><![CDATA[Bijay Kumar]]></dc:creator>
		<pubDate>Sat, 28 Nov 2026 15:15:00 +0000</pubDate>
				<category><![CDATA[Blazor]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=3092</guid>

					<description><![CDATA[If you&#8217;re choosing between Blazor Server and WebAssembly for a .NET 10 app, use Server for internal line-of-business apps near their data and WebAssembly for offline or static-hosted apps. For public apps, pick Auto. That&#8217;s my verdict on Blazor Server vs WebAssembly. I ran one order-desk component all three ways. On localhost, Server was clickable ... <a title="Blazor Server vs WebAssembly vs Auto: Which Should You Choose?" class="read-more" href="https://aspdotnethelp.com/blazor-server-vs-webassembly/" aria-label="Read more about Blazor Server vs WebAssembly vs Auto: Which Should You Choose?">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">If you&#8217;re choosing between Blazor Server and WebAssembly for a .NET 10 app, use Server for internal line-of-business apps near their data and WebAssembly for offline or static-hosted apps. For public apps, pick Auto. That&#8217;s my verdict on <strong>Blazor Server vs WebAssembly</strong>.</p>



<p class="wp-block-paragraph">I ran one order-desk component all three ways. On localhost, Server was clickable after 311 ms, while WebAssembly needed 1,588 ms and a 2,214 KB download. Here&#8217;s the full comparison.</p>



<h2 class="wp-block-heading">Blazor Server vs WebAssembly vs Auto at a Glance</h2>



<p class="wp-block-paragraph">Every number below comes from my Release builds on <a href="https://aspdotnethelp.com/whats-new-in-dotnet-10/">.NET 10</a>, measured in headless Edge on localhost, so read timings as best case.</p>



<figure class="wp-block-table"><table><thead><tr><th>Feature</th><th>Blazor Server</th><th>Blazor WebAssembly</th><th>Auto (Blazor Web App)</th></tr></thead><tbody><tr><td>Where your C# runs</td><td>Server, over a SignalR circuit</td><td>Browser, on .NET for WebAssembly</td><td>Server first, browser on later visits</td></tr><tr><td>First-visit download</td><td>60 KB</td><td>2,214 KB</td><td>2,208 KB, mostly in the background</td></tr><tr><td>Clickable after (localhost)</td><td>311 ms</td><td>1,588 ms</td><td>500 ms; 1,545 ms on reload</td></tr><tr><td>Median click (localhost)</td><td>5.7 ms</td><td>2.9 ms</td><td>10.5 ms; 3.4 ms on reload</td></tr><tr><td>Works offline</td><td>No</td><td>Yes, as a standalone PWA</td><td>No</td></tr><tr><td>Hosting</td><td>ASP.NET Core server</td><td>Any static host or CDN (standalone)</td><td>ASP.NET Core server</td></tr><tr><td>Content in the first HTML</td><td>Yes, prerendered</td><td>No (standalone)</td><td>Yes, prerendered</td></tr><tr><td>App code in the browser</td><td>No</td><td>Yes, as .wasm files</td><td>Yes, the .Client project</td></tr><tr><td>Server memory per user</td><td>~168 KB of heap per circuit (my test)</td><td>None</td><td>Only during Server visits</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Auto is a render mode of a Blazor Web App; how to apply it is in my <a href="https://aspdotnethelp.com/blazor-render-modes/">Blazor render modes guide</a>.</p>



<h2 class="wp-block-heading">The Sample Order Desk Used for Every Blazor Test</h2>



<p class="wp-block-paragraph">One component runs in all four setups: a button that counts packed orders and a list of five US orders. It prints <code>RendererInfo.Name</code> so each test shows where it ran.</p>



<pre class="wp-block-code"><code>
@using System.Globalization

&lt;div class=&quot;board&quot; data-interactive=&quot;@RendererInfo.IsInteractive.ToString().ToLower()&quot;&gt;
    &lt;h1&gt;Order desk&lt;/h1&gt;
    &lt;p&gt;Running on: &lt;strong id=&quot;where&quot;&gt;@RendererInfo.Name&lt;/strong&gt;&lt;/p&gt;
    &lt;button id=&quot;pack&quot; @onclick=&quot;Pack&quot; disabled=&quot;@(!RendererInfo.IsInteractive)&quot;&gt;Pack next order&lt;/button&gt;
    &lt;p id=&quot;packed&quot;&gt;Orders packed: @packed&lt;/p&gt;
    &lt;ul id=&quot;orders&quot;&gt;
        @foreach (var o in orders)
        {
            &lt;li&gt;#@o.Id @o.City, @o.State: $@o.Total.ToString(&quot;0.00&quot;, CultureInfo.InvariantCulture)&lt;/li&gt;
        }
    &lt;/ul&gt;
&lt;/div&gt;

@code {
    private int packed;

    private readonly Order[] orders =
    [
        new(1001, &quot;Austin&quot;, &quot;TX&quot;, 84.50m),
        new(1002, &quot;Denver&quot;, &quot;CO&quot;, 129.99m),
        new(1003, &quot;Raleigh&quot;, &quot;NC&quot;, 42.75m),
        new(1004, &quot;Boise&quot;, &quot;ID&quot;, 310.00m),
        new(1005, &quot;Tampa&quot;, &quot;FL&quot;, 67.20m)
    ];

    private void Pack() =&gt; packed++;

    private record Order(int Id, string City, string State, decimal Total);
}
</code></pre>



<p class="wp-block-paragraph">In the Blazor Web App it lives in the <code>.Client</code> project, and three one-line pages give it a mode. Here&#8217;s the Server one; the others swap in <code>InteractiveWebAssembly</code> and <code>InteractiveAuto</code>:</p>



<pre class="wp-block-code"><code>
@page &quot;/server&quot;
@rendermode InteractiveServer

&lt;PageTitle&gt;Server desk&lt;/PageTitle&gt;

&lt;OrdersBoard /&gt;
</code></pre>



<p class="wp-block-paragraph">The standalone app shows the same file on its home page (new to components? see <a href="https://aspdotnethelp.com/blazor-components/">how Blazor components work</a>). Both apps came from .NET 10 templates:</p>



<pre class="wp-block-code"><code>dotnet new blazor --interactivity Auto --empty -o W11BlazorWeb
dotnet new blazorwasm --pwa --empty -o W11BlazorPwa</code></pre>



<p class="wp-block-paragraph">Since .NET 8, &#8220;Blazor Server&#8221; means a Blazor Web App created with <code>--interactivity Server</code>, the setup my <a href="https://aspdotnethelp.com/blazor-tutorial-for-beginners/">Blazor tutorial for beginners</a> uses. My <code>dotnet new list blazor</code> still shows <code>blazorserver</code>, but only for net6.0 and net7.0.</p>



<h2 class="wp-block-heading">Download Size: How Big Is a Blazor WebAssembly App?</h2>



<p class="wp-block-paragraph">Same app, same five orders, now on disk: I published the standalone app with <code>dotnet publish -c Release</code>. Its <code>_framework</code> folder held 42 files and 8,903 KB, plus Brotli copies totaling 2,669 KB.</p>



<p class="wp-block-paragraph">The browser skips some of it, but the first visit to /wasm still pulled 33 <code>.wasm</code> files, 2,202 KB over the wire. The /server page moved 60 KB in total, mostly <code>blazor.web.js</code>.</p>



<p class="wp-block-paragraph">Auto pulled 2,208 KB too, just after the page was usable. The Web App&#8217;s client bundle (2,697 KB of Brotli files) matched the standalone one, and AOT compilation would make it bigger, not smaller.</p>



<h2 class="wp-block-heading">Which Loads Faster: Time to Interactive for Server, WebAssembly and Auto</h2>



<p class="wp-block-paragraph">Same five orders on every page, and a fresh Edge profile each time. I recorded when the five orders first showed and when the button became clickable. The last column repeats the test with Edge throttled to 20 Mbps and 40 ms of latency.</p>



<figure class="wp-block-table"><table><thead><tr><th>Same page, cold visit</th><th>Orders visible</th><th>Clickable</th><th>Clickable at 20 Mbps</th></tr></thead><tbody><tr><td>Blazor Server</td><td>85 ms</td><td>311 ms</td><td>609 ms</td></tr><tr><td>WebAssembly in a Web App</td><td>42 ms</td><td>1,588 ms</td><td>2,656 ms</td></tr><tr><td>Auto, first visit</td><td>57 ms</td><td>500 ms</td><td>513 ms</td></tr><tr><td>Auto, reload (cached)</td><td>55 ms</td><td>1,545 ms</td><td>&#8211;</td></tr><tr><td>Standalone WASM PWA</td><td>1,734 ms</td><td>1,734 ms</td><td>4,536 ms</td></tr><tr><td>Standalone PWA, reload</td><td>821 ms</td><td>821 ms</td><td>&#8211;</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Prerendering is why the Web App rows show orders in under 100 ms, even for WebAssembly. The standalone PWA shows nothing until .NET has booted, 1,734 ms here and 4,536 ms on the throttled run.</p>



<p class="wp-block-paragraph"><strong>Note:</strong> the Auto reload surprised me. It moved only 16 KB, yet the button took 1,545 ms, because starting the cached WebAssembly runtime still costs a second or more. The first Server-backed visit was faster at 500 ms.</p>



<h2 class="wp-block-heading">Click Latency: Blazor Server SignalR Round Trip vs WebAssembly</h2>



<p class="wp-block-paragraph">Same five orders, now clicked: I pressed Pack next order 20 times on each page and timed each click until the counter changed. On localhost the medians were 5.7 ms for Server and 2.9 ms for WebAssembly.</p>



<p class="wp-block-paragraph">With Edge&#8217;s 40 ms latency setting, the Server median rose to 24.4 ms while WebAssembly stayed at 2.7 ms. Every Server click is a network round trip; WebAssembly never leaves the browser.</p>



<p class="wp-block-paragraph">Microsoft Learn recommends UI latency of 250 ms or less, which hotel Wi-Fi can break. Calls through <a href="https://aspdotnethelp.com/blazor-javascript-interop/">Blazor JavaScript interop</a> pay the same round trip on Server.</p>



<h2 class="wp-block-heading">How Much Server Memory Does a Blazor Server Circuit Use?</h2>



<p class="wp-block-paragraph">Each browser tab on a Server page gets its own circuit, which keeps your component state in server memory. My demo-only <code>/heap</code> endpoint reports the managed heap after a full garbage collection.</p>



<p class="wp-block-paragraph">With no visitors the heap was 4,339 KB. With 30 Edge tabs open on /server it was 9,386 KB, about 168 KB per circuit for this tiny component.</p>



<p class="wp-block-paragraph">That&#8217;s the managed heap only, not the whole process. Microsoft&#8217;s planning number is about 250 KB per circuit for a Hello World app, so a page holding a <a href="https://aspdotnethelp.com/blazor-quickgrid/">QuickGrid</a> with thousands of rows will cost far more. WebAssembly uses none of it.</p>



<h2 class="wp-block-heading">Offline and PWA: Does Blazor WebAssembly Work Without a Server?</h2>



<p class="wp-block-paragraph">Yes, but only a standalone app built as a PWA, and only once it&#8217;s published. I visited the PWA, stopped my static file host, reloaded and clicked three times. It kept working, because the service worker had cached every file.</p>



<p class="wp-block-paragraph">Then I stopped the server behind the Blazor Server page and clicked. The circuit was gone, so you get the reconnect dialog and nothing else.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1100" height="327" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-webassembly-pwa-offline-vs-blazor-server-reconnect.png" alt="Blazor WebAssembly PWA keeps working with Orders packed: 3 after its static host was stopped, while the Blazor Server page shows the Rejoining the server dialog and Orders packed: 0" class="wp-image-3122" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-webassembly-pwa-offline-vs-blazor-server-reconnect.png 1100w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-webassembly-pwa-offline-vs-blazor-server-reconnect-300x89.png 300w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-webassembly-pwa-offline-vs-blazor-server-reconnect-1024x304.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-webassembly-pwa-offline-vs-blazor-server-reconnect-768x228.png 768w" sizes="auto, (max-width: 1100px) 100vw, 1100px" /><figcaption class="wp-element-caption">Server stopped: the standalone PWA keeps working, Blazor Server waits to rejoin</figcaption></figure>
</div>


<p class="wp-block-paragraph">A Blazor Web App can&#8217;t do this, Auto included, because its pages come from ASP.NET Core.</p>



<h2 class="wp-block-heading">Hosting Blazor: Static Files vs an ASP.NET Core Server</h2>



<p class="wp-block-paragraph">The standalone app is just files. Its <code>Program.cs</code> mounts the root component and registers an <code>HttpClient</code>:</p>



<pre class="wp-block-code"><code>using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using W11BlazorPwa;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add&lt;App&gt;(&quot;#app&quot;);
builder.RootComponents.Add&lt;HeadOutlet&gt;(&quot;head::after&quot;);

builder.Services.AddScoped(sp =&gt; new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

await builder.Build().RunAsync();</code></pre>



<p class="wp-block-paragraph">Its project file uses the WebAssembly SDK, and the <code>ServiceWorker</code> item is what the PWA option adds:</p>



<pre class="wp-block-code"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.BlazorWebAssembly&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;OverrideHtmlAssetPlaceholders&gt;true&lt;/OverrideHtmlAssetPlaceholders&gt;
    &lt;ServiceWorkerAssetsManifest&gt;service-worker-assets.js&lt;/ServiceWorkerAssetsManifest&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Components.WebAssembly&quot; Version=&quot;10.0.13&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Components.WebAssembly.DevServer&quot; Version=&quot;10.0.13&quot; PrivateAssets=&quot;all&quot; /&gt;
  &lt;/ItemGroup&gt;

  &lt;ItemGroup&gt;
    &lt;ServiceWorker Include=&quot;wwwroot\service-worker.js&quot; PublishedContent=&quot;wwwroot\service-worker.published.js&quot; /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;</code></pre>



<p class="wp-block-paragraph">I served the published <code>wwwroot</code> folder from a tiny Node.js static host that sends the <code>.br</code> files. Azure Static Web Apps or any CDN does the same job.</p>



<p class="wp-block-paragraph">Server and Auto need ASP.NET Core. Here&#8217;s the server <code>Program.cs</code>, trimmed for this test, with the <code>/heap</code> endpoint at the end:</p>



<pre class="wp-block-code"><code>
using W11BlazorWeb.Components;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents()
    .AddInteractiveWebAssemblyComponents();

var app = builder.Build();

app.UseExceptionHandler(&quot;/Error&quot;, createScopeForErrors: true);
app.UseAntiforgery();

app.MapStaticAssets();
app.MapRazorComponents&lt;App&gt;()
    .AddInteractiveServerRenderMode()
    .AddInteractiveWebAssemblyRenderMode()
    .AddAdditionalAssemblies(typeof(W11BlazorWeb.Client._Imports).Assembly);

// demo only: managed heap after a full GC, to estimate memory per circuit
app.MapGet(&quot;/heap&quot;, () =&gt; $&quot;{GC.GetTotalMemory(forceFullCollection: true) / 1024:N0} KB&quot;);

app.Run();
</code></pre>



<p class="wp-block-paragraph">The server project references the <code>.Client</code> project, which builds the WebAssembly half:</p>



<pre class="wp-block-code"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;BlazorDisableThrowNavigationException&gt;true&lt;/BlazorDisableThrowNavigationException&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;ProjectReference Include=&quot;..\W11BlazorWeb.Client\W11BlazorWeb.Client.csproj&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Components.WebAssembly.Server&quot; Version=&quot;10.0.13&quot; /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;</code></pre>



<pre class="wp-block-code"><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.BlazorWebAssembly&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;NoDefaultLaunchSettingsFile&gt;true&lt;/NoDefaultLaunchSettingsFile&gt;
    &lt;StaticWebAssetProjectMode&gt;Default&lt;/StaticWebAssetProjectMode&gt;
    &lt;BlazorDisableThrowNavigationException&gt;true&lt;/BlazorDisableThrowNavigationException&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Components.WebAssembly&quot; Version=&quot;10.0.13&quot; /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;</code></pre>



<pre class="wp-block-code"><code>using Microsoft.AspNetCore.Components.WebAssembly.Hosting;

var builder = WebAssemblyHostBuilder.CreateDefault(args);

await builder.Build().RunAsync();</code></pre>



<p class="wp-block-paragraph">When a standalone app calls an API on another domain, that API needs <a href="https://aspdotnethelp.com/cors-in-aspnet-core/">CORS in ASP.NET Core</a> turned on for the app&#8217;s origin.</p>



<h2 class="wp-block-heading">SEO and Prerendering in Blazor Server vs WebAssembly</h2>



<p class="wp-block-paragraph">Search engines and link previews read the first HTML response. I fetched both apps with curl and filtered for the orders:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1492" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-server-prerendered-html-vs-webassembly-index-html.png" alt="VS Code showing OrdersBoard.razor and a terminal where curl of the Blazor Web App /server page returns all five orders in HTML, while the standalone WebAssembly index.html only has the loading-progress spinner" class="wp-image-3123" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-server-prerendered-html-vs-webassembly-index-html.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-server-prerendered-html-vs-webassembly-index-html-278x300.png 278w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-server-prerendered-html-vs-webassembly-index-html-950x1024.png 950w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-server-prerendered-html-vs-webassembly-index-html-768x828.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">curl output: prerendered orders from the Web App, a spinner from standalone WASM</figcaption></figure>
</div>


<p class="wp-block-paragraph">The Web App page had 5 order rows (and <code>Static</code>, the prerendered pass). The standalone index.html had 0, just a spinner.</p>



<p class="wp-block-paragraph">Prerendering does mean <code>OnInitializedAsync</code> runs twice, once for the HTML and once when the page goes interactive, as I show in <a href="https://aspdotnethelp.com/blazor-component-lifecycle/">the Blazor component lifecycle</a>.</p>



<h2 class="wp-block-heading">Security: What Blazor WebAssembly Sends to the Browser</h2>



<p class="wp-block-paragraph">With WebAssembly, your compiled code is a public download. Since .NET 8, assemblies ship in the Webcil format with a <code>.wasm</code> extension instead of <code>.dll</code>, but they&#8217;re still .NET assemblies anyone can save and decompile.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1384" height="1492" src="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-webassembly-publish-framework-wasm-files.png" alt="VS Code with W11BlazorPwa.csproj open and a terminal listing the published _framework .wasm files, ending with W11BlazorPwa.os4h01p9q4.wasm, the app&#x27;s own assembly" class="wp-image-3124" srcset="https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-webassembly-publish-framework-wasm-files.png 1384w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-webassembly-publish-framework-wasm-files-278x300.png 278w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-webassembly-publish-framework-wasm-files-950x1024.png 950w, https://aspdotnethelp.com/wp-content/uploads/2026/11/vs-code-blazor-webassembly-publish-framework-wasm-files-768x828.png 768w" sizes="auto, (max-width: 1384px) 100vw, 1384px" /><figcaption class="wp-element-caption">dotnet publish output: the app&#8217;s assembly ships as a .wasm file</figcaption></figure>
</div>


<p class="wp-block-paragraph">My publish produced 35 <code>.wasm</code> files, including <code>W11BlazorPwa.os4h01p9q4.wasm</code>. So never put connection strings, API keys or pricing rules in a WebAssembly or Auto component.</p>



<p class="wp-block-paragraph">Keep them on the server behind an API, like the one in my <a href="https://aspdotnethelp.com/aspnet-core-web-api-crud-ef-core/">ASP.NET Core Web API with EF Core</a> guide, protected with <a href="https://aspdotnethelp.com/jwt-authentication-aspnet-core/">JWT authentication</a>. Blazor Server code never leaves your server.</p>



<h2 class="wp-block-heading">Scaling Blazor Server: Circuits, Sticky Sessions and Azure SignalR Service</h2>



<p class="wp-block-paragraph">A circuit lives on one server, so your load balancer needs sticky sessions. On Azure App Service, turn WebSockets on and leave session affinity on.</p>



<p class="wp-block-paragraph">Scoped services live as long as the circuit, not one request, which changes how <a href="https://aspdotnethelp.com/dependency-injection-lifetimes-aspnet-core/">DI lifetimes in ASP.NET Core</a> behave.</p>



<p class="wp-block-paragraph">For many concurrent users or several regions, Microsoft recommends Azure SignalR Service. WebAssembly needs none of this.</p>



<h2 class="wp-block-heading">When to Use Blazor Server, WebAssembly or Auto</h2>



<ul class="wp-block-list">
<li>Internal line-of-business app on a fast network, data next to the server: <strong>Blazor Server</strong>.</li>

<li>Field app that must keep working offline, or you only have static hosting: <strong>standalone WebAssembly PWA</strong>.</li>

<li>Public site that needs fast first paint and SEO, with heavy interactivity later: <strong>Auto</strong>.</li>

<li>Mostly content pages with a few forms: static SSR, with Server only on the pages that need clicks.</li>
</ul>



<p class="wp-block-paragraph">In short, Server wins on first load, privacy and simplicity, WebAssembly wins on offline use, static hosting and click speed, and Auto gives you a 500 ms first visit with in-browser clicks afterward.</p>



<p class="wp-block-paragraph">More Blazor and ASP.NET Core reading on the site:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/blazor-tutorials/">Every Blazor tutorial on one page</a></li>

<li><a href="https://aspdotnethelp.com/blazor-forms-validation/">Blazor forms and validation with EditForm</a></li>

<li><a href="https://aspdotnethelp.com/minimal-api-vs-controllers-aspnet-core/">Minimal APIs vs controllers for your Blazor backend</a></li>

<li><a href="https://aspdotnethelp.com/upgrade-dotnet-8-to-dotnet-10/">Upgrading a .NET 8 Blazor app to .NET 10</a></li>
</ul>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-bh110000001" class="rank-math-list-item">
<h3 class="rank-math-question ">Is Blazor Server faster than Blazor WebAssembly?</h3>
<div class="rank-math-answer ">

<p>For the first load, yes: 311 ms versus 1,588 ms in my localhost test. After loading, WebAssembly clicks skip the network.</p>

</div>
</div>
<div id="faq-question-bh110000002" class="rank-math-list-item">
<h3 class="rank-math-question ">What is the difference between Blazor Server and a Blazor Web App?</h3>
<div class="rank-math-answer ">

<p>Blazor Web App is the .NET 8+ project template. Blazor Server is what you get when that app uses the Interactive Server render mode. The old blazorserver template only targets .NET 7 and earlier.</p>

</div>
</div>
<div id="faq-question-bh110000003" class="rank-math-list-item">
<h3 class="rank-math-question ">Can I switch from Blazor WebAssembly to Blazor Server later?</h3>
<div class="rank-math-answer ">

<p>Yes. Components are the same in every hosting model; the work is moving direct DbContext calls behind an API, since WebAssembly code can&#8217;t reach your database.</p>

</div>
</div>
<div id="faq-question-bh110000004" class="rank-math-list-item">
<h3 class="rank-math-question ">Does Blazor WebAssembly work offline?</h3>
<div class="rank-math-answer ">

<p>A standalone app created with dotnet new blazorwasm &#8211;pwa works offline after the first visit, once published. Blazor Server and Blazor Web App pages need the server.</p>

</div>
</div>
<div id="faq-question-bh110000005" class="rank-math-list-item">
<h3 class="rank-math-question ">Should I use Blazor Auto render mode for a new app?</h3>
<div class="rank-math-answer ">

<p>Use it for public apps that need a fast first visit and less server load later. It needs a .Client project and services registered on both sides. See <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/hosting-models?view=aspnetcore-10.0" target="_blank" rel="noopener">ASP.NET Core Blazor hosting models</a> on Microsoft Learn.</p>

</div>
</div>
</div>
</div>]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: aspdotnethelp.com @ 2026-12-02 22:17:04 by W3 Total Cache
-->