📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

A lookup by account number has an index on a varchar(20) column, yet from your .NET API it scans the whole table and uses lots of CPU, while the same query typed into SSMS seeks instantly. The plan shows CONVERT_IMPLICIT. How do you diagnose it and fix it in EF Core, Dapper and ADO.NET?

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.

Senior Debugging Advanced dapper debugging ef-core implicit-conversion indexes sql-server

🎯 Key points

  • System.String maps to nvarchar by default in ADO.NET, Dapper (nvarchar(4000)) and EF Core when the model says Unicode
  • nvarchar has higher type precedence, so the varchar column is converted: CONVERT_IMPLICIT on the column
  • SQL collations (SQL_Latin1_General_CP1_CI_AS) scan; Windows collations may get a dynamic range seek but still cost more and estimate worse
  • Find it: PlanAffectingConvert warning, plan cache XML search, Query Store top CPU queries
  • EF Core: IsUnicode(false) or HasColumnType("varchar(20)") so parameters are AnsiString with a size
  • Dapper: DbString { IsAnsi = true, Length = n }; ADO.NET: SqlDbType.VarChar with Size, never AddWithValue
  • Model and database must agree: scaffold or check column types after database-first changes
  • Fix once at the mapping layer and add a test that asserts parameter types or plan shape

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"'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."


Where the nvarchar comes from

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

Which direction hurts

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can connect a SQL plan symptom to .NET parameter typing and fix it at the right layer.

Green flags

  • Explains data type precedence and that the column side is converted
  • Reproduces with sp_executesql and the app's real parameter types
  • Knows the defaults in ADO.NET, Dapper and EF Core and the exact fixes
  • Searches the plan cache for other affected queries and adds a regression guard

Red flags

  • Blames parameter sniffing without checking types
  • Adds an index hint or FORCESEEK
  • Fixes one query with CAST and moves on

📚 Learn in depth

1. Data type precedence

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

2. Why the collation matters

  • SQL collations (names starting 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.
  • Windows collations (such as 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.

3. What the plan shows

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.

4. The app side in detail

  • ADO.NET AddWithValue("@p", "AC-1001") infers nvarchar(7); each different length creates a different plan cache entry, too.
  • Dapper maps 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.
  • EF Core decides from the model: 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.

5. Fix options

  1. Make the app send varchar (best, no schema change).
  2. Change the column to nvarchar if it genuinely needs Unicode (doubles storage for ASCII data, index rebuild, migration).
  3. In SQL Server 2019+, a UTF-8 collation on varchar columns stores Unicode in varchar, but the parameter type from .NET must still match.

6. Under load

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.

Try it yourself

  1. Create a 5-million-row table with a 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.
  2. Repeat with the column under Latin1_General_100_CI_AS and see the dynamic seek.
  3. Write a Dapper call with and without DbString and capture both statements in Extended Events (rpc_completed).
  4. Configure an EF Core model with and without IsUnicode(false) and compare ToQueryString() and the logged parameter types.
  5. Run the plan cache query from the code example on a real database and count the affected queries.

💻 Code

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?;
    }
}

⚠ Common mistakes

  • Mistake: Testing with a literal in SSMS and concluding the query is fine. Why it is wrong: the literal is 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.
  • Mistake: Using 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.
  • Mistake: Leaving string properties unconfigured in a hand-written EF Core model over varchar columns. Why it is wrong: without configuration EF Core treats strings as Unicode and sends 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.
  • Mistake: Globally mapping 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.
  • Mistake: Wrapping the parameter in 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.
  • Mistake: Assuming a Windows collation makes it harmless. Why it is wrong: the dynamic seek still costs CPU and estimates degrade. Instead: match types regardless of collation.
  • Mistake: Converting the column to 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the column being converted rather than the parameter. Why: Checks the general sargability rules this case belongs to.
    How to answer

    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.
    • An implicit conversion of the column (e.g. 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.

  2. When: Candidate mentions EF Core string property mapping or nvarchar(max). Why: Checks string type choices in EF Core models.
    How to answer

    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.

  3. When: Candidate mentions AddWithValue inferring the parameter length. Why: Checks understanding of parameter size and plan reuse.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Account lookup scanning 40 million rows after a hand-written EF Core model
Situation
A [banking] API on Azure SQL (General Purpose, [8] vCores) looked up accounts by `AccountNo varchar(20)` about [300] times a second. The team had replaced a scaffolded EF Core model with a hand-written one during a refactor.
Signals
After the release, database CPU climbed from [20]% to [75]%, Application Insights showed the lookup dependency p95 at [420] ms instead of [3] ms, and Query Store's regressed queries report listed the lookup.
Investigation
Query Store showed the old query (index seek) and a new query id with a clustered index scan reading [40 million] rows. The new query text declared `@__accountNo_0 nvarchar(4000)` and the plan had a `PlanAffectingConvert` warning with `CONVERT_IMPLICIT` on `AccountNo`. The plan cache query found [11] other statements with the same warning, all on varchar columns of the same model.
Resolution
Immediate: plan forcing could not help because the parameter declaration changed the query text, so it was a new query in Query Store; we hotfixed the model with `IsUnicode(false).HasMaxLength(20)` on the affected properties and redeployed, and CPU dropped within minutes. Long-term: added `AreUnicode(false)` as the convention with explicit overrides for the few nvarchar columns, and checked the generated migration was empty to confirm no schema change.
Prevention
An integration test that compares the EF Core model's column types with the database schema (`INFORMATION_SCHEMA.COLUMNS`); a test capturing generated SQL for key queries and asserting `varchar(20)` parameters; a weekly job running the plan cache query and alerting on new seek-affecting conversions.

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.

↩ Usually asked after

More in Indexes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me