Covers how .NET strings become nvarchar parameters, why an nvarchar parameter against a varchar column converts the column and blocks seeks (collation nuances), finding it in plans and the plan cache, and fixing it with IsUnicode(false)/HasColumnType, DbString/AnsiString and typed SqlParameters.
In .NET a string becomes an nvarchar parameter by default (ADO.NET AddWithValue, Dapper sends nvarchar(4000), EF Core when the property is Unicode). nvarchar has higher data type precedence than varchar, so SQL Server converts the column, not the parameter: CONVERT_IMPLICIT(nvarchar, AccountNo). With a SQL collation that means a scan of every row; with a Windows collation you may get a dynamic seek, but with worse estimates. SSMS was fast because the literal there was varchar.
Diagnose with the plan warning ('Type conversion may affect seek plan'), Query Store and a plan cache search. Fix at the mapping layer: EF Core IsUnicode(false)/HasColumnType("varchar(20)"), Dapper DbString { IsAnsi = true }, ADO.NET SqlDbType.VarChar with a size. Trade-off: changing the column to nvarchar also works but doubles storage.
"'Fast in SSMS, slow from the app' with CONVERT_IMPLICIT in the plan is almost always a parameter type mismatch. In SSMS someone types WHERE AccountNo = 'AC-1001', which is a varchar literal, so it seeks. From .NET a string becomes an nvarchar parameter by default: AddWithValue infers nvarchar, Dapper sends nvarchar(4000), and EF Core sends nvarchar if the model thinks the property is Unicode. Because nvarchar has higher data type precedence than varchar, SQL Server can't convert the parameter down without potentially losing characters, so it converts the column up, for every row. With the common SQL_Latin1_General collation that turns the seek into a scan; with a Windows collation the optimiser can sometimes build a dynamic range and still seek, but estimates and CPU are worse.
To diagnose it I capture the real parameterised statement, from Query Store or Application Insights dependency telemetry, rather than retyping it. The actual plan shows the scan with a yellow warning, 'Type conversion in expression may affect seek plan', and the predicate contains CONVERT_IMPLICIT on the column. Then I search the plan cache for PlanAffectingConvert warnings to see how many other queries have the same problem, because it's rarely just one. For example, at [company] we [found the account lookup scanning a [40]-million-row table on every call; fixing the EF Core mapping took the query from [~180,000] logical reads to [4] and database CPU from [70]% to [25]%].
The fix belongs in the mapping, not in each query. In EF Core I configure the property as IsUnicode(false) with a max length or HasColumnType varchar(20), so EF sends AnsiString parameters with the right size. In Dapper I use DbString with IsAnsi true. In plain ADO.NET I declare SqlDbType.VarChar with a size and stop using AddWithValue. The mistake I see is 'fixing' it with a CAST in the SQL or a query hint. Make the app speak the column's type, then add a test so a future model change can't silently bring the scan back."
| Client | Default for string |
Fix |
|---|---|---|
ADO.NET AddWithValue |
nvarchar(len) (also plan-cache bloat from varying lengths) |
Add("@p", SqlDbType.VarChar, 20) |
| Dapper anonymous object | nvarchar(4000) |
new DbString { Value = v, IsAnsi = true, Length = 20 } |
| EF Core, property not configured | nvarchar(max) or nvarchar(450) key |
.IsUnicode(false).HasMaxLength(20) or HasColumnType("varchar(20)") |
| EF Core, model says varchar | varchar(20) |
Already correct |
| Column | Parameter | What is converted | Seek? |
|---|---|---|---|
varchar |
nvarchar |
Column | Scan (SQL collation) / dynamic seek (Windows collation) |
nvarchar |
varchar |
Parameter | Yes |
int |
varchar |
Parameter (int wins) | Yes, but errors on bad input |
varchar(20) |
varchar(8000) |
Nothing | Yes |
A [banking] API's account lookup ran 300 times a second. The column was varchar(20) but the EF Core model had been hand-written without configuration, so every call sent nvarchar(4000) and scanned 40 million rows. Adding IsUnicode(false).HasMaxLength(20) (no migration needed, the database already matched) cut p95 from 420 ms to 3 ms and reduced the Azure SQL tier by two vCores.
Checks whether the candidate can connect a SQL plan symptom to .NET parameter typing and fix it at the right layer.
Green flags
Red flags
When two sides of a comparison differ, SQL Server converts the lower-precedence type to the higher one. Part of the order: datetime2 > ... > int > ... > nvarchar > ... > varchar. So:
WHERE AccountNo (varchar) = @p (nvarchar)
-> CONVERT_IMPLICIT(nvarchar(20), [AccountNo], 0) = @p
-> the index is sorted by varchar values under its collation, not by the converted value
SQL_, such as SQL_Latin1_General_CP1_CI_AS): varchar and nvarchar values are compared with different rules, so the optimiser cannot map an nvarchar value to a varchar range. Result: a scan with the conversion evaluated for every row.Latin1_General_100_CI_AS_SC): varchar and nvarchar share comparison rules, so SQL Server can compute a dynamic range (GetRangeThroughConvert) and still seek. The plan is more complex and cardinality estimates are often poor.SQL_Latin1_General_CP1_CI_AS is the default for Azure SQL Database and for many on-premises installs, so the scan case is the common one. Check yours with SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation') and the column's own collation in sys.columns.
Clustered Index Scan PK_Accounts Actual rows read: 40,112,883
Predicate: CONVERT_IMPLICIT(nvarchar(20),[AccountNo],0) = [@p0]
Warning: Type conversion in expression (CONVERT_IMPLICIT(...)) may affect
"SeekPlan" in query plan choice
In the plan XML this is a PlanAffectingConvert element with ConvertIssue="Seek Plan". A ConvertIssue="Cardinality Estimate" warning is the milder variant.
AddWithValue("@p", "AC-1001") infers nvarchar(7); each different length creates a different plan cache entry, too.string to DbType.String (nvarchar(4000) for short strings). DbString { IsAnsi = true, Length = 20, IsFixedLength = false } sends varchar(20). A global SqlMapper.AddTypeMap(typeof(string), DbType.AnsiString) works only if the whole database is varchar.IsUnicode(false) maps to varchar and parameters become DbType.AnsiString with the configured size. Models scaffolded with dotnet ef dbcontext scaffold carry the column types across and get this right; hand-written code-first models, or models where someone changed the column to varchar in the database without updating the model, send nvarchar.varchar (best, no schema change).nvarchar if it genuinely needs Unicode (doubles storage for ASCII data, index rebuild, migration).varchar columns stores Unicode in varchar, but the parameter type from .NET must still match.A scan per call is a CPU problem first: at a few hundred calls a second it saturates the database, starves other queries and, on Azure SQL, pushes you into a higher tier. Because each scan reads the whole table into the buffer pool, it also evicts useful pages, so unrelated queries slow down too. That is why one mismatched parameter can look like a general capacity problem.
varchar(20) indexed column under SQL_Latin1_General_CP1_CI_AS; query it with an nvarchar and a varchar parameter via sp_executesql and compare reads.Latin1_General_100_CI_AS and see the dynamic seek.DbString and capture both statements in Extended Events (rpc_completed).IsUnicode(false) and compare ToQueryString() and the logged parameter types.Diagnose: find queries in the plan cache with seek-affecting conversions.
WITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')
SELECT TOP (50)
qs.execution_count,
qs.total_worker_time / qs.execution_count / 1000 AS avg_cpu_ms,
qs.total_logical_reads / qs.execution_count AS avg_reads,
c.value('@Expression', 'nvarchar(400)') AS conversion,
SUBSTRING(st.text, 1, 300) AS query_start
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
CROSS APPLY qp.query_plan.nodes('//Warnings/PlanAffectingConvert[@ConvertIssue="Seek Plan"]') AS w(c)
ORDER BY qs.total_worker_time DESC;
-- Reproduce exactly as the app sends it
EXEC sp_executesql N'SELECT AccountId FROM dbo.Accounts WHERE AccountNo = @p0', N'@p0 nvarchar(4000)', @p0 = N'AC-1001'; -- scan
EXEC sp_executesql N'SELECT AccountId FROM dbo.Accounts WHERE AccountNo = @p0', N'@p0 varchar(20)', @p0 = 'AC-1001'; -- seek
Fix in EF Core 10: tell the model the column is non-Unicode with a length; parameters become varchar(20).
namespace Bank.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public sealed class Account
{
public int AccountId { get; set; }
public required string AccountNo { get; set; }
}
public sealed class AccountConfiguration : IEntityTypeConfiguration<Account>
{
public void Configure(EntityTypeBuilder<Account> b)
{
b.Property(a => a.AccountNo)
.IsUnicode(false) // varchar, so parameters are DbType.AnsiString
.HasMaxLength(20); // sized parameter: varchar(20), one plan
b.HasIndex(a => a.AccountNo).IsUnique();
}
}
// Optional: make non-Unicode the default for a database that is mostly varchar.
public sealed class BankContext(DbContextOptions<BankContext> options) : DbContext(options)
{
public DbSet<Account> Accounts => Set<Account>();
protected override void ConfigureConventions(ModelConfigurationBuilder builder) =>
builder.Properties<string>().AreUnicode(false);
protected override void OnModelCreating(ModelBuilder modelBuilder) =>
modelBuilder.ApplyConfiguration(new AccountConfiguration());
}
Fix in Dapper and ADO.NET: declare the type and size explicitly.
namespace Bank.Data;
using System.Data;
using Dapper;
using Microsoft.Data.SqlClient;
public sealed class AccountLookup(string connectionString)
{
public async Task<int?> DapperAsync(string accountNo, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
var args = new { AccountNo = new DbString { Value = accountNo, IsAnsi = true, Length = 20 } };
return await conn.QuerySingleOrDefaultAsync<int?>(new CommandDefinition(
"SELECT AccountId FROM dbo.Accounts WHERE AccountNo = @AccountNo", args, cancellationToken: ct));
}
public async Task<int?> AdoNetAsync(string accountNo, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
await using var cmd = new SqlCommand("SELECT AccountId FROM dbo.Accounts WHERE AccountNo = @AccountNo", conn);
cmd.Parameters.Add("@AccountNo", SqlDbType.VarChar, 20).Value = accountNo; // not AddWithValue
await conn.OpenAsync(ct);
return await cmd.ExecuteScalarAsync(ct) as int?;
}
}
varchar; the app sends nvarchar, so you test a different query. Instead: reproduce with sp_executesql and the exact parameter types from Query Store or a trace.AddWithValue for strings. Why it is wrong: it infers nvarchar(len), causing conversions and one plan per length. Instead: Parameters.Add with SqlDbType.VarChar and a size.nvarchar parameters (scaffolded models carry the varchar type and are usually fine). Instead: IsUnicode(false) and HasMaxLength, or a convention in ConfigureConventions, and a test comparing the model with the schema.string to AnsiString in Dapper on a database that also has nvarchar columns. Why it is wrong: values for the nvarchar columns are sent as varchar, so characters outside the code page (for example Vietnamese or Chinese names) are silently replaced with '?' on insert, and nvarchar comparisons get the conversion instead. Instead: DbString { IsAnsi = true } per varchar parameter, or the global map only for all-varchar databases.CAST(@p AS varchar(20)) in every query. Why it is wrong: it hides the cause and is easy to forget in new queries. Instead: fix the mapping once.nvarchar as a reflex. Why it is wrong: it doubles storage for ASCII data and needs a migration and index rebuilds. Instead: do it only if the data really needs Unicode.This is the most common seek-killer in .NET shops, and it is invisible in code review because the C# looks correct. The senior move is to treat it as a mapping-layer defect: find every affected query from the plan cache in one go, fix the model or the data access helper once, and add a guard so it cannot regress.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Fix the mapping (IsUnicode(false), DbString, SqlDbType.VarChar) | Column is varchar and should stay so | Code change only | Column must store Unicode |
| EF Core convention AreUnicode(false) | Database is almost all varchar | One line; must override Unicode columns | Mixed databases with many nvarchar columns |
| Change column to nvarchar | Data genuinely needs Unicode (names, addresses) | Storage, index rebuild, migration | ASCII-only codes and identifiers |
| UTF-8 collation on varchar (2019+) | Want Unicode in varchar storage | Collation change, testing | Existing indexes and joins with other collations |
Measure before and after with Query Store (CPU and logical reads per execution) and check the plan cache query returns nothing for the fixed tables.
A predicate is SARGable (Search ARGument-able) when the optimiser can turn it into a seek range on an index. The rule: leave the column bare and put any calculation on the other side.
YEAR(OrderDate) = 2026 scans; OrderDate >= '2026-01-01' AND OrderDate < '2027-01-01' seeks.Price * 1.1 > 100 scans; Price > 100 / 1.1 seeks.varchar column vs nvarchar parameter) often scans; match types.LIKE 'abc%' seeks; LIKE '%abc' cannot.ISNULL(col, 0) = 0 scans; col = 0 OR col IS NULL seeks.When the expression is unavoidable, index a persisted computed column. Trade-off: the rewrite is free; the computed column costs storage and writes.
An nvarchar(max) column cannot be a key column of a B-tree index (clustered or non-clustered); it can only sit in INCLUDE or a full-text index, so a lookup on it scans. Values that do not fit in the row (over 8,000 bytes) move to LOB pages, so reading them costs extra I/O, and online index operations were historically restricted. The optimiser also estimates row size from the declared type, assuming a max column is about half-full of a large value, so sorts and hash joins get oversized memory grants that waste memory and reduce concurrency. EF Core maps an unconfigured string to nvarchar(max), so the fix is to give strings realistic lengths with HasMaxLength, a convention, or [MaxLength], and keep max for genuine documents.
AddWithValue infers the parameter type from the .NET value: a string becomes nvarchar(n) where n is that value's length, so 'Smith' is sent as nvarchar(5) and 'Nguyen' as nvarchar(6). The parameter declaration is part of the statement text, so SQL Server compiles and caches a separate plan per length. On a busy system that means extra compile CPU, plan cache memory taken from the buffer pool, and useful plans evicted sooner. If the column is varchar, the same call also causes a CONVERT_IMPLICIT scan.
Detect it as many rows sharing one query_hash with different plan_handles in sys.dm_exec_query_stats, or many query ids for one query in Query Store. Fix with Parameters.Add("@p", SqlDbType.VarChar, 20); Dapper and EF Core already send fixed sizes.
How to tell it (STAR)
**S:** At [company], right after a data-layer refactor, our account lookup went from 3 ms to over 400 ms and database CPU hit [75]%. **T:** I had to find the cause quickly and make sure it couldn't come back. **A:** Query Store showed the plan had flipped to a scan, and the new query text declared nvarchar(4000) for a varchar column, with a CONVERT_IMPLICIT warning. I searched the plan cache and found [11] more queries with the same problem, fixed the EF Core mapping with a non-Unicode convention, and added a test that compares model types with the schema. **R:** p95 returned to [3] ms, CPU fell to [20]%, and we scaled the database down two vCores.
Last updated 23 Nov 2026.