A senior .NET engineer owns the design and quality of large modules. They choose patterns, review code, solve production issues such as memory leaks, deadlocks and slow queries, and guide junior developers. They plan database migrations, set coding standards, improve performance and work closely with architects, testers and product owners to deliver reliable releases on schedule. They also own estimates and technical documentation for their area.
System design Performance profiling Code reviews SQL tuning Mentoring
Solved for this roleStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
A page listing 100 orders with customer names runs 101 SQL queries. What is the problem and how do you fix it?
This is the N+1 problem: one query loads the orders, then lazy loading fires a separate query for each order's Customer. Fix it by loading everything in one query, either with Include(o => o.Customer) or better with a projection: Select(o => new OrderListDto(o.Id, o.Total, o.Customer.Name)), which fetches only needed columns via a join. Turn on EF Core logging to spot such patterns early.
A delegate is a type-safe reference to a method with a specific signature, similar to a function pointer but checked by the compiler. You can pass methods as parameters, store them and call them later. Delegates can be multicast, holding several methods that run in order. Lambdas, LINQ, events and callbacks are all built on delegates, and the built-in Func and Action types cover most needs.
virtual marks a base method as replaceable. override in a derived class replaces it, so calls through a base reference run the derived version. new hides the base method instead: a call through a base reference still runs the base version, and only a derived-type reference sees the new one. Method hiding is usually a sign of a design problem, and the compiler warns when you hide without writing new.
04
Show bulk update and delete with ExecuteUpdate and ExecuteDelete.
// mark all unpaid invoices older than 30 days as overdue
int updated = await db.Invoices
.Where(i => !i.IsPaid && i.DueDate < DateTime.UtcNow.AddDays(-30))
.ExecuteUpdateAsync(s => s
.SetProperty(i => i.Status, "Overdue")
.SetProperty(i => i.UpdatedAt, DateTime.UtcNow));
// delete old logs
int deleted = await db.AuditLogs
.Where(l => l.CreatedAt < cutoff)
.ExecuteDeleteAsync();
These run a single SQL UPDATE or DELETE without loading entities, available since EF Core 7. They bypass the change tracker.
05
Your team debates wrapping EF Core in a generic repository. What is your view?
DbContext already implements Repository and Unit of Work, so a thin generic repository with GetAll and Add often adds code while hiding useful features like Include, projections and AsNoTracking. I prefer either using DbContext directly in services, or specific repositories with meaningful methods like GetOverdueInvoicesAsync that encapsulate queries. For tests, use the SQLite in-memory provider or Testcontainers rather than mocking DbSet.
06
Write a recursive CTE that lists an employee hierarchy with levels.
WITH Org AS (
SELECT Id, Name, ManagerId, 0 AS Lvl
FROM Employees
WHERE ManagerId IS NULL -- anchor: CEO
UNION ALL
SELECT e.Id, e.Name, e.ManagerId, o.Lvl + 1
FROM Employees e
JOIN Org o ON e.ManagerId = o.Id -- recursive part
)
SELECT REPLICATE(' ', Lvl) + Name AS Hierarchy, Lvl
FROM Org
OPTION (MAXRECURSION 100);
The anchor query runs once and the recursive part repeats until no new rows are found.
07
A read-only product listing endpoint in EF Core uses a lot of memory and CPU. What simple change helps, and why?
By default, EF Core tracks every entity it loads so it can detect changes on SaveChanges, which costs memory and CPU. AsNoTracking tells EF Core not to track the results, making read-only queries faster and lighter. Use it for lists, reports and GET endpoints where you will not update the data. AsNoTrackingWithIdentityResolution avoids duplicate instances of the same entity in results while still skipping tracking.
Single Responsibility: a class has one reason to change. Open/Closed: extend behaviour without editing existing code. Liskov Substitution: derived types must work wherever the base type is expected. Interface Segregation: prefer small, focused interfaces over one fat interface. Dependency Inversion: depend on abstractions, not concrete classes. In ASP.NET Core, injecting IEmailSender into a controller instead of creating SmtpClient directly applies dependency inversion.
09
How are exceptions handled in async code, and what is AggregateException?
When you await a faulted task, the original exception is rethrown, so normal try-catch works. If you block with .Wait() or .Result, the exception is wrapped in AggregateException. With Task.WhenAll, await throws only the first exception, but the returned task's Exception property holds all of them in an AggregateException. Unobserved exceptions from fire-and-forget tasks are silently lost, so always await or log them.
10
Your multi-tenant SaaS app keeps all tenants in one database. How do you make sure EF Core queries never return another tenant's data?
Add a TenantId column to every tenant-owned entity and a global query filter such as HasQueryFilter(e => e.TenantId == _tenantId), where the tenant ID comes from a scoped provider that reads the authenticated user's claim. Set TenantId automatically in SaveChanges for new rows. Index TenantId, write integration tests that try cross-tenant access, audit every IgnoreQueryFilters call, and consider SQL Server row-level security as a second layer of defence.
11
Profiling shows a hot cache-lookup method returning Task<T> allocates millions of Task objects. Would ValueTask help?
ValueTask<T> is a struct that avoids allocating a Task when a method usually completes synchronously, for example when a value is served from an in-memory cache most of the time. In very hot paths this reduces GC pressure. The rules are stricter: await a ValueTask only once, do not await it concurrently, and do not call .Result before it completes. For normal application code, Task is simpler and recommended.
12
How do you use an explicit transaction in EF Core across multiple SaveChanges calls?
await using var tx = await db.Database.BeginTransactionAsync();
try
{
db.Orders.Add(order);
await db.SaveChangesAsync();
var stock = await db.Stocks.SingleAsync(s => s.ProductId == order.ProductId);
stock.Quantity -= order.Quantity;
await db.SaveChangesAsync();
await tx.CommitAsync();
}
catch
{
await tx.RollbackAsync();
throw;
}
A single SaveChanges is already transactional; explicit transactions are needed when you combine several saves or raw SQL into one unit.
13
An Orders table has 50 million rows and queries are slowing down, but most reports only need the last 12 months. What would you do?
First check indexes and query plans, since good indexing often solves it. Then archive older data: move rows older than a set period to an archive table or database in small batches during off-peak hours, keeping reports on history available separately. For ongoing growth, use table partitioning by month on OrderDate, which enables fast partition switching and lets queries scan only relevant partitions. Agree retention rules with the business first.
14
What are System.Threading.Channels and when would you use them?
Channels provide fast, thread-safe, async producer-consumer queues. A producer writes with await writer.WriteAsync and a consumer reads with await foreach over reader.ReadAllAsync. Bounded channels apply back-pressure by making producers wait when full. They are useful inside one process, for example an API that accepts uploads quickly and hands them to a background worker. For durable or cross-service queues use a broker like RabbitMQ or Azure Service Bus.
15
Several threads update an in-memory Dictionary cache in a singleton service and you see corrupted data and exceptions. What would you use instead?
System.Collections.Concurrent provides thread-safe collections: ConcurrentDictionary, ConcurrentQueue, ConcurrentStack, ConcurrentBag and BlockingCollection. They use fine-grained locking or lock-free techniques, so multiple threads can read and write without your own lock. Use ConcurrentDictionary for in-memory caches in singleton services. Note that GetOrAdd may run the value factory more than once under contention, so keep the factory side-effect free or wrap it in Lazy<T>.
16
A singleton CacheService injects AppDbContext, and users start seeing stale data and occasional 'a second operation was started on this context' errors. What is wrong?
This is a captive dependency: a scoped DbContext is captured by a singleton, so one context lives forever and is shared by all requests across threads. DbContext is not thread-safe and its change tracker grows stale. Fix it by injecting IServiceScopeFactory or IDbContextFactory<AppDbContext> into the singleton and creating a short-lived context per operation. Enabling ValidateScopes in development catches this at startup.
17
A stored procedure is fast for most customers but very slow for one large customer, and sometimes slow for everyone after a restart. What could cause this?
This is parameter sniffing. SQL Server compiles a plan using the first parameter values it sees and reuses it. A plan built for a small customer, using index seeks, can be terrible for a huge one, and vice versa. Fixes include OPTION (RECOMPILE) for that statement, OPTIMIZE FOR, splitting logic for skewed values, or Query Store plan forcing. SQL Server 2022 adds Parameter Sensitive Plan optimisation to keep multiple plans.
18
Tell me about a time you led a team to deliver a complex feature.
As tech lead (Situation) I owned a vendor-payments module touching Angular, three APIs and SQL Server. My task was to deliver it in six weeks with four developers. I broke it into vertical slices, defined API contracts first, set up feature flags and reviewed every pull request within a day. When one developer struggled with EF Core, I paired with them. Result: we released on time with no critical bugs and two juniors grew into module owners.
19
What does ConfigureAwait(false) do and is it needed in ASP.NET Core?
By default await captures the current SynchronizationContext and resumes on it. ConfigureAwait(false) tells the runtime it can resume on any thread pool thread, which avoids deadlocks in UI and old ASP.NET apps and slightly reduces overhead. ASP.NET Core has no SynchronizationContext, so it is not required in application code there. It is still recommended in general-purpose libraries that might be used by WPF or WinForms apps.
20
What techniques improve EF Core query performance?
Project only needed columns with Select instead of loading full entities. Use AsNoTracking for reads. Avoid N+1 with Include or projections. Page with Skip and Take or keyset paging. Add proper indexes via HasIndex. Use ExecuteUpdate and ExecuteDelete for bulk changes. For hot queries, compiled queries with EF.CompileAsyncQuery and DbContext pooling with AddDbContextPool reduce overhead. Always check generated SQL with logging or ToQueryString.
21
How does EF Core handle many-to-many relationships?
Since EF Core 5, you can define collection navigations on both sides, such as Student.Courses and Course.Students, and EF Core creates a hidden join table automatically. If the join needs extra data, like EnrolledOn or Grade, create an explicit join entity Enrollment with two foreign keys and configure it with UsingEntity or two one-to-many relationships. Querying works naturally with Include or projections through the navigations.
22
How do you explain good object-oriented design to a junior developer on your team?
I avoid theory first. I take a real piece of our code, like a controller that talks to the database directly, and pair with them to move logic into a service behind an interface, then write a unit test with a mock. Seeing how much easier testing becomes explains SOLID better than slides. I then review their next pull request with specific comments and point them to one or two good examples in our codebase.
23
You must rename a column and split a Name field into FirstName and LastName in a production database with live data. How do you deploy safely?
Avoid destructive one-step migrations. Use an expand-and-contract approach: first add new nullable columns, deploy code that writes both old and new, and backfill data with a script in batches. Then switch reads to the new columns, and only in a later release drop the old column. Generate idempotent SQL scripts, review them with the DBA, take a backup and test on a production copy first.
A SynchronizationContext represents where continuations should run. WPF and WinForms have one that marshals work back to the UI thread, so after await you can update controls safely. Classic ASP.NET had one tied to the request. ASP.NET Core and console apps have none, so continuations run on any thread pool thread. Understanding it explains why .Result deadlocks in UI apps but often not in ASP.NET Core.
25
What are ACID properties and the transaction isolation levels in SQL Server?
ACID means Atomicity (all or nothing), Consistency (rules hold), Isolation (transactions do not interfere) and Durability (committed data survives crashes). Isolation levels are READ UNCOMMITTED (dirty reads allowed), READ COMMITTED (the default), REPEATABLE READ, SERIALIZABLE (strictest) and SNAPSHOT, which uses row versions so readers do not block writers. Read Committed Snapshot Isolation is often enabled to reduce blocking in busy OLTP apps.
An event is a delegate wrapped with restricted access. Outside the class, subscribers can only add or remove handlers with += and -=; they cannot invoke the event or overwrite the whole list with =. This protects the publisher. The standard pattern uses EventHandler<TEventArgs> with sender and args. Remember to unsubscribe long-lived subscriptions, otherwise the publisher keeps subscribers alive and causes memory leaks.
A view is a saved SELECT query that acts like a virtual table; it simplifies complex joins and can restrict which columns users see, but by default it stores no data. An indexed view has a unique clustered index, so SQL Server physically stores and maintains its results, which speeds up heavy aggregations. The cost is slower writes on base tables, and it requires SCHEMABINDING and deterministic expressions.
29
Which design patterns do you commonly see in ASP.NET Core projects?
Dependency Injection is built in. The Repository and Unit of Work patterns wrap data access, although DbContext already implements them. Factory creates objects by type, for example IHttpClientFactory. Strategy swaps algorithms, such as different tax or discount rules, behind one interface. Options pattern binds configuration to classes. Middleware is a Chain of Responsibility, and Mediator libraries implement CQRS by sending commands to handlers.
30
Users report intermittent errors saying their transaction was chosen as a deadlock victim. How do you investigate and fix it?
A deadlock happens when two sessions each hold a lock the other needs. Get the deadlock graph from the system_health Extended Events session to see the statements and objects involved. Common fixes: access tables in the same order in all code paths, keep transactions short, add indexes so queries lock fewer rows, and consider RCSI. Also add retry logic in the app, since EF Core's SQL Server execution strategy can retry deadlocks.
public async IAsyncEnumerable<Order> GetOrdersAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
await foreach (var o in _db.Orders.AsNoTracking().AsAsyncEnumerable().WithCancellation(ct))
yield return o;
}
// consumer
await foreach (var order in service.GetOrdersAsync())
Console.WriteLine(order.Id);
Items are produced and consumed one at a time asynchronously. ASP.NET Core can stream an IAsyncEnumerable result as JSON without buffering the whole list.
32
A PaymentService has a large if-else on payment type (card, UPI, netbanking, wallet) and every new method means editing it. How do you refactor?
Apply the Strategy pattern with the Open/Closed principle. Define IPaymentProcessor with a Type property and ProcessAsync method, and create one class per method. Register all of them in DI, inject IEnumerable<IPaymentProcessor>, and pick the right one by type, possibly through a dictionary. Adding a new payment type is now a new class plus a registration, with no change to existing, tested code.
33
A frequent query on Orders filtered by CustomerId shows expensive key lookups in its execution plan. How would you fix it?
A covering index contains every column a query needs, so SQL Server answers it from the index alone without key lookups to the clustered index. INCLUDE adds non-key columns to the leaf level only, keeping the index key small. For SELECT Name, Total FROM Orders WHERE CustomerId = 5, an index on CustomerId INCLUDE (Name, Total) covers it. Do not include too many columns, since every index slows writes.
34
A complex reporting query written in EF Core is slow and hard to tune. When would you move it to Dapper?
Dapper is a micro-ORM that maps raw SQL results to objects with very low overhead. It suits read-heavy reports, complex hand-tuned queries and stored procedures where you want full SQL control. EF Core offers change tracking, migrations, LINQ and relationships, which speed up CRUD development. Many projects use both: EF Core for writes and normal features, Dapper for performance-critical queries, sharing the same connection string.
35
How do you handle requirements that keep changing during a sprint?
In one sprint (Situation) the product owner changed a checkout screen twice. My task was to deliver without losing quality. I asked for a quick meeting to understand the reason, split the work into a stable API part and a flexible UI part, and agreed with the team which change would move to the next sprint. Result: we shipped the core flow on time, and the team started confirming acceptance criteria before sprint planning.
36
Give an example of a Liskov Substitution Principle violation and how to fix it.
A classic case is Square inheriting Rectangle. Setting Width on a square also changes Height, so code that sets width 5 and height 4 and expects area 20 breaks. Another real case is a ReadOnlyRepository that inherits Repository and throws NotSupportedException on Save. The fix is to model shared behaviour with interfaces such as IShape or IReadRepository and IWriteRepository, so subclasses never weaken the contract.
37
A legacy ASP.NET MVC app on .NET Framework hangs when a controller calls GetDataAsync().Result. Why, and how do you fix it?
This is the classic sync-over-async deadlock. .Result blocks the request thread, which holds the ASP.NET synchronization context. When the awaited task completes, its continuation tries to resume on that same context, which is blocked, so neither can proceed. The real fix is async all the way: make the action async and await the call. Where that is impossible, ConfigureAwait(false) inside the library avoids capturing the context.
38
Write a LINQ query that joins orders with customers and returns customer name and order total.
var result = orders
.Join(customers,
o => o.CustomerId,
c => c.Id,
(o, c) => new { c.Name, o.Total })
.ToList();
// query syntax
var result2 = (from o in orders
join c in customers on o.CustomerId equals c.Id
select new { c.Name, o.Total }).ToList();
Join is an inner join. For a left join use GroupJoin with DefaultIfEmpty, or the LeftJoin operator added in .NET 10.
39
Under load, an API's response time jumps to many seconds while CPU stays low. Thread count keeps rising. What is likely happening?
This pattern points to thread pool starvation. Some code is blocking threads with .Result, .Wait(), Thread.Sleep or synchronous I/O, so pool threads are stuck waiting and the pool injects new threads slowly. Confirm with dotnet-counters, watching thread pool queue length and thread count, and a dump showing many threads blocked in Wait. Fix by making the call chain fully async; raising minimum threads is only a temporary patch.
40
An EF Core query that includes Items and Payments for each order returns a huge, duplicated result set. What is happening and how do split queries help?
When you Include two or more collection navigations, such as Orders with Items and Payments, EF Core generates one query with joins. Rows multiply: 10 items times 5 payments return 50 rows per order, duplicating data heavily. AsSplitQuery() tells EF Core to run separate queries per collection and stitch results together, avoiding duplication. The trade-off is more round trips and possible inconsistency without a transaction.
Frequently asked questions
What does a Senior .NET Engineer do?
A senior .NET engineer owns the design and quality of large modules. They choose patterns, review code, solve production issues such as memory leaks, deadlocks and slow queries, and guide junior developers. They plan database migrations, set coding standards, improve performance and work closely with architects, testers and product owners to deliver reliable releases on schedule. They also own estimates and technical documentation for their area.
Which skills are tested in a Senior .NET Engineer interview?
Expect questions on System design, Performance profiling, Code reviews, SQL tuning, Mentoring. Most rounds also ask you to explain a project and solve one practical problem live.
How do I prepare for a Senior .NET Engineer interview?
Revise Async Programming and Multithreading, Entity Framework Core, OOP in C#, SQL Server and T-SQL first using the topic sheets, practise the questions on this page aloud, then do one full mock interview to practise timing.