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.
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 --"));$ 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.- Step 1
1.String concat: data + SQL become one text
- Step 2
2.The user's quote closes the string
- Step 3
3.' OR 1=1: condition true for every row
- Step 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.
static List<Product> Search( ShopDb db, string term) => db.Products .FromSql($""" SELECT * FROM Products WHERE Name = {term} """) .OrderBy(p => p.Price) .ToList();$ 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:| API | Returns | Safe with user input? |
|---|---|---|
| FromSqlRaw("..." + term) | Entities | No: 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.
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);// 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}");$ 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.
$ dotnet run -- checkpoint SELECT "p"."Id", "p"."Category", ..., "p"."UpdatedAt" FROM ( SELECT * FROM Products ) AS "p" WHERE NOT ("p"."IsDeleted")Rows: 556.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.
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); }}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; }}$ 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- Step 1
1.Remove() marks the entry Deleted
- Step 2
2.SaveChangesAsync -> SavingChangesAsync (interceptor)
- Step 3
3.Stamp: Deleted -> Unchanged, IsDeleted = true, UpdatedAt = now
- Step 4
4.EF sends UPDATE ... SET IsDeleted, UpdatedAt
- Step 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.
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);$ 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.
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}");$ dotnet run -- dapperSteel Bottle 399Yoga Mat 69956.7 Comparison: EF Core vs Dapper
| Point | EF Core | Dapper |
|---|---|---|
| Style | Full ORM, LINQ -> SQL | Micro ORM, you write SQL |
| Change tracking / migrations | Yes | No |
| Query filters / interceptors | Yes | No, handle it in SQL |
| Best for | CRUD, relationships, business logic | Complex reporting SQL, full control |
| Performance | Close to Dapper with AsNoTracking + projection | Slightly 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.
// 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: 656.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.