SkillPilotAI

Advanced EF Core and Dapper

Beyond plain LINQ, real apps need raw SQL without SQL injection, soft delete that no query can forget, automatic audit fields, and sometimes a lighter tool like Dapper. This note covers FromSql, SqlQuery, global query filters, SaveChanges interceptors and EF Core vs Dapper.

56.1 The problem: SQL built from strings

  • The search term is concatenated straight into the SQL inside FromSqlRaw.
  • "Yoga Mat" returns 1 product; "' OR 1=1 --" returns all 6.
  • The build even shows warning EF1003, but developers often ignore it.
C#
static List<Product> SearchBad(    ShopDb db, string term)    => db.Products.FromSqlRaw(        "SELECT * FROM Products " +        "WHERE Name = '" + term + "'")        .ToList(); Print(SearchBad(db, "Yoga Mat"));Print(SearchBad(db, "' OR 1=1 --"));
Output
$ dotnet run -- bugExecuted DbCommand (38ms) [Parameters=[], ...]  SELECT * FROM Products WHERE Name = 'Yoga Mat'Found 1: Yoga MatExecuted DbCommand (0ms) [Parameters=[], ...]  SELECT * FROM Products WHERE Name = '' OR 1=1 --'Found 6: Mixer Grinder, Steel Bottle, Pressure Cooker, Cricket Bat, Yoga Mat, Fidget Spinner$ dotnet buildwarning EF1003: Method 'FromSqlRaw' inserts concatenated strings directly into the SQL, without any protection against SQL injection.Build succeeded.
How the injection works
  1. 1.String concat: data + SQL become one text

  2. 2.The user's quote closes the string

  3. 3.' OR 1=1: condition true for every row

  4. 4.--: the rest becomes a comment

Fix: values go in parameters, not in the SQL text

56.2 Fix: FromSql with interpolation

  • FromSql takes a FormattableString, not a plain string: SQL text and values stay separate.
  • Each interpolated value becomes a parameter (@p0); the database treats it only as data.
  • The attack input now gives Found 0. LINQ (OrderBy) still composes on top of the raw SQL.
C#
static List<Product> Search(    ShopDb db, string term)    => db.Products        .FromSql($"""            SELECT * FROM Products            WHERE Name = {term}            """)        .OrderBy(p => p.Price)        .ToList();
Output
$ dotnet run -- fromsqlExecuted DbCommand (103ms) [Parameters=[p0='?' (Size = 8)], ...]  FROM (      SELECT * FROM Products      WHERE Name = @p0  ) AS "p"  ...  ORDER BY "p"."Price"Found 1: Yoga MatExecuted DbCommand (0ms) [Parameters=[p0='?' (Size = 11)], ...]  ...Found 0:
APIReturnsSafe with user input?
FromSqlRaw("..." + term)EntitiesNo: concatenation = injection
FromSql($"... {term}")Entities (LINQ composable, query filters apply)Yes: values become parameters
Database.SqlQuery<T>($"...")Any type (non-entity, e.g. a report record)Yes: parameters
Database.ExecuteSql($"...")Rows affected (data-changing SQL)Yes: parameters

56.3 Soft delete: global query filter

  • Soft delete: set IsDeleted = true instead of deleting, so history stays.
  • Now every query needs IsDeleted = false; forget it once and deleted data shows up.
  • HasQueryFilter adds the condition to every LINQ query on the entity. EF Core 10 lets you name it ("SoftDelete").
  • Admin screens use IgnoreQueryFilters(["SoftDelete"]) to see deleted rows too: Active 5, All 6.
C#
protected override void OnConfiguring(    DbContextOptionsBuilder o) => o    .UseSqlite("Data Source=shop.db")    .AddInterceptors(new AuditInterceptor())    .LogTo(Console.WriteLine, SqlOnly); protected override void OnModelCreating(    ModelBuilder b) => b.Entity<Product>()    .HasQueryFilter("SoftDelete",        p => !p.IsDeleted);
C#
// normal query: filter is addedvar list = await db.Products.ToListAsync();Console.WriteLine($"Active: {list.Count}"); // admin screen: include deletedvar all = await db.Products    .IgnoreQueryFilters(["SoftDelete"])    .ToListAsync();Console.WriteLine($"All: {all.Count}");
Output
$ dotnet run -- filter  SELECT "p"."Id", "p"."Category", ..., "p"."UpdatedAt"  FROM "Products" AS "p"  WHERE NOT ("p"."IsDeleted")Active: 5  SELECT "p"."Id", "p"."Category", ..., "p"."UpdatedAt"  FROM "Products" AS "p"All: 6
  • Checkpoint: FromSql($"SELECT * FROM Products") still returns 5 rows, because EF wraps raw SQL in a subquery and applies the filter outside it.
Output
$ dotnet run -- checkpoint  SELECT "p"."Id", "p"."Category", ..., "p"."UpdatedAt"  FROM (      SELECT * FROM Products  ) AS "p"  WHERE NOT ("p"."IsDeleted")Rows: 5

56.4 SaveChanges interceptor: audit + soft delete

  • Setting CreatedAt / UpdatedAt by hand everywhere is error prone.
  • An interceptor is a hook that runs your code in the middle of SaveChanges; SavingChangesAsync runs just before the SQL is sent.
  • Stamp: Added -> CreatedAt, Modified -> UpdatedAt.
  • The trick: a Deleted entry becomes Unchanged with IsDeleted = true, so Remove() sends an UPDATE, not a DELETE.
C#
public class AuditInterceptor    : SaveChangesInterceptor{    public override        ValueTask<InterceptionResult<int>>        SavingChangesAsync(            DbContextEventData e,            InterceptionResult<int> result,            CancellationToken ct = default)    {        Stamp(e.Context!, DateTime.UtcNow);        return base.SavingChangesAsync(            e, result, ct);    }}
C#
foreach (var e in db.ChangeTracker             .Entries<Product>()){    if (e.State == EntityState.Added)        e.Entity.CreatedAt = now;    if (e.State == EntityState.Modified)        e.Entity.UpdatedAt = now;    if (e.State == EntityState.Deleted)    {        e.State = EntityState.Unchanged;        e.Entity.IsDeleted = true;        e.Entity.UpdatedAt = now;    }}
Output
$ dotnet run -- delete  UPDATE "Products" SET "IsDeleted" = @p0, "UpdatedAt" = @p1  WHERE "Id" = @p2  RETURNING 1;$ dotnet run -- audit  UPDATE "Products" SET "Price" = @p0, "UpdatedAt" = @p1Mixer Grinder | False | 20:41:23 |Steel Bottle | False | 20:41:23 |Pressure Cooker | False | 20:41:23 |Cricket Bat | False | 20:41:23 | 20:42:37Yoga Mat | False | 20:41:23 |Fidget Spinner | True | 20:41:23 | 20:42:19
db.Products.Remove(spinner) with the interceptor
  1. 1.Remove() marks the entry Deleted

  2. 2.SaveChangesAsync -> SavingChangesAsync (interceptor)

  3. 3.Stamp: Deleted -> Unchanged, IsDeleted = true, UpdatedAt = now

  4. 4.EF sends UPDATE ... SET IsDeleted, UpdatedAt

  5. 5.Row stays; the query filter hides it from normal queries

ExecuteDelete / ExecuteUpdate skip this path

56.5 SqlQuery: non-entity results

  • A category-wise sales report is not an entity: Database.SqlQuery<T> maps raw SQL to any type (CategoryTotal record).
  • Values still become parameters. Not an entity, so the query filter does not apply: write IsDeleted = 0 yourself.
  • For data-changing raw SQL, ExecuteSql works the same way.
C#
var report = await db.Database    .SqlQuery<CategoryTotal>($"""        SELECT Category, COUNT(*) AS Items,               SUM(Price) AS Total        FROM Products        WHERE IsDeleted = 0        GROUP BY Category        """)    .ToListAsync();foreach (var r in report)    Console.WriteLine(r);
Output
$ dotnet run -- reportCategoryTotal { Category = Kitchen, Items = 3, Total = 4797 }CategoryTotal { Category = Sports, Items = 2, Total = 2098 }

56.6 Dapper: a micro ORM

  • No change tracking, no migrations: it runs your SQL and maps the result to objects.
  • QueryAsync<ProductRow>(sql, new { max = 1000 }): @max is a parameter, so no injection risk.
  • Dapper knows nothing about EF query filters: add IsDeleted = 0 yourself.
C#
await using var conn = new SqliteConnection(    "Data Source=shop.db"); var cheap = await conn.QueryAsync<ProductRow>(    """    SELECT Id, Name, Price FROM Products    WHERE Price < @max AND IsDeleted = 0    ORDER BY Price    """,    new { max = 1000 }); foreach (var p in cheap)    Console.WriteLine($"{p.Name} {p.Price}");
Output
$ dotnet run -- dapperSteel Bottle 399Yoga Mat 699

56.7 Comparison: EF Core vs Dapper

PointEF CoreDapper
StyleFull ORM, LINQ -> SQLMicro ORM, you write SQL
Change tracking / migrationsYesNo
Query filters / interceptorsYesNo, handle it in SQL
Best forCRUD, relationships, business logicComplex reporting SQL, full control
PerformanceClose to Dapper with AsNoTracking + projectionSlightly faster raw mapping
  • Many teams use both: writes in EF Core, heavy reports in Dapper.

56.8 Common mistakes

  • ExecuteDeleteAsync for soft-deletable data: it bypasses the change tracker, the interceptor never runs, and the row is gone for good. Use ExecuteUpdateAsync to set IsDeleted and UpdatedAt.
  • Thinking interpolation means injection: in FromSql interpolation is the safe way; the danger is FromSqlRaw + concatenation.
  • Dropping EF Core because "Dapper is always faster": with AsNoTracking and projection the gap is tiny in most APIs.
  • Overriding only SavingChangesAsync: override SavingChanges too for the sync SaveChanges.
C#
// Wrong: interceptor skipped, row gone for goodawait db.Products    .Where(p => p.Name == "Steel Bottle")    .ExecuteDeleteAsync();// Rows in table: 5 // Right: soft delete, row staysawait db.Products    .Where(p => p.Name == "Steel Bottle")    .ExecuteUpdateAsync(s => s        .SetProperty(p => p.IsDeleted, true)        .SetProperty(p => p.UpdatedAt,            DateTime.UtcNow));// Rows in table: 6

56.9 Interview tips

  • Raw SQL: FromSql / SqlQuery / ExecuteSql turn interpolated values into DbParameters; never concatenate in FromSqlRaw.
  • Soft delete: a named global query filter + IgnoreQueryFilters only on admin screens.
  • Auditing: a SaveChanges interceptor sets audit fields and turns Remove into an UPDATE; ExecuteUpdate/Delete skip it.
  • EF Core for CRUD and relationships, Dapper for heavy hand-written reports, added only after measuring.