Other

One EF Core line stops implicit conversion on varchar columns

DEV Community: #csharp Umer Farooq
Other

EF Core sends C# string parameters as nvarchar by default, so on varchar columns SQL Server converts the column and scans the index instead of seeking. The post shows how `IsUnicode(false)` cut logical reads from 887 to 3 on a 200,000-row table.

Key points

  • EF Core's default sends an NVARCHAR(4000) parameter, visible as `Size = 4000` without a DbType.
  • The plan difference is stark: an Index Scan reads 200,000 rows, a matching-type Index Seek reads one.
  • The fix is `IsUnicode(false).HasMaxLength(100)`, which logs the parameter as `DbType = AnsiString`.
  • The `[Unicode(false)]` annotation or `HasColumnType("varchar(100)")` produce the same parameter type.
  • For an all-varchar database, `Properties<string>().AreUnicode(false)` in `ConfigureConventions` applies it globally.
  • Dapper needs `DbString { IsAnsi = true }` and ADO.NET needs `SqlDbType.VarChar` to avoid the same trap.
  • A plan-cache query for `CONVERT_IMPLICIT` on columns in WHERE or JOIN clauses finds offenders in production.

Real-world use

  • Legacy databases full of varchar columns accessed through hand-written EF Core models
  • Frequently executed lookups that fetch a single row by email or username
  • Existing data access code written with Dapper or ADO.NET

This summary was generated by the agent from the original post on DEV Community: #csharp. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message