AI assistants now write a big share of the C# in our pull requests. The code compiles, the tests pass locally and the demo goes well. Then it reaches production and something breaks: a query times out, an endpoint leaks another customer's data, or the app runs out of sockets at peak load.
The problem isn't that AI writes bad code. It writes plausible code, tuned for the happy path it was shown. Production is where the unhappy paths live. This post covers the mistakes I see most often in AI-generated C#, why "works on my machine" keeps happening, and the checks I now run before anything ships.
What went wrong:
Each snippet below is the kind of code an assistant hands back when you ask for "an endpoint that does X". Every one of them works in a demo. For each, I cover why the assistant wrote it, what breaks in production, and how to catch it in review.
1. SQL built with string interpolation
// AI-generated: works, and is injectable var orders = await _db.Orders .FromSqlRaw($"SELECT * FROM Orders WHERE CustomerName = '{name}'") .ToListAsync(); // Fix: FromSql turns the interpolated value into a SQL parameter (EF Core 7+) var orders = await _db.Orders .FromSql($"SELECT * FROM Orders WHERE CustomerName = {name}") .ToListAsync(); Why the AI wrote it: FromSqlRaw with $"..." appears all over older blog posts and forum answers, so it is a high-probability completion. The interpolation looks like parameterization but isn't: the string is fully built before EF Core ever sees it. FromSql takes a FormattableString instead, so EF can turn each {value} into a real @p0 parameter.
What happens in prod: Any search box or query-string filter that reaches this code becomes an attack surface. A name like x' OR '1'='1 returns every customer's orders. If the database login has broad rights, '; DROP TABLE Orders;-- is far worse. Report filters, search screens and "export to Excel" endpoints are the usual victims, because they take free text.
Catch it in review: Search the diff for FromSqlRaw, ExecuteSqlRaw, SqlCommand and string concatenation near SQL keywords. Any user-supplied value inside the SQL string itself is an automatic reject. As a second line of defence, give the app's database login only the rights it needs, and never db_owner or sa in production.
2. No authorization or ownership check
// AI-generated: any logged-in user can read any invoice by guessing IDs [HttpGet("{id}")] public async Task<IActionResult> GetInvoice(int id) => Ok(await _db.Invoices.FindAsync(id)); // Fix: require auth, scope to the caller, return a DTO instead of the entity [Authorize] [HttpGet("{id}")] public async Task<IActionResult> GetInvoice(int id, CancellationToken ct) { var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); var invoice = await _db.Invoices .Where(i => i.Id == id && i.OwnerId == userId) .Select(i => new InvoiceDto(i.Id, i.Amount, i.DueDate)) .FirstOrDefaultAsync(ct); return invoice is null ? NotFound() : Ok(invoice); } Why the AI wrote it: You asked for "an endpoint that returns an invoice by ID", and that is exactly what you got. The assistant doesn't know your tenancy model, or that invoice 1043 belongs to a different client. It skips the ownership check because you never mentioned one.
What happens in prod: This is Broken Object Level Authorization, number one in the OWASP API Security Top 10. A logged-in user changes /invoices/1042 to /invoices/1043 and reads another company's billing. Returning the raw entity makes it worse, because internal notes, cost prices, audit fields and navigation properties all get serialized. With lazy loading switched on, one request can pull in half the object graph.
Catch it in review: Every action needs a clear answer to "who may call this, and for which records?" Look for FindAsync(id) with no user or tenant filter, and for actions that return EF entity types. In multi-tenant apps, a global query filter such as HasQueryFilter(i => i.TenantId == _tenant.Id) makes the safe path the default, so a forgotten Where doesn't leak data.
3. Blocking on async code
// AI-generated public IActionResult GetRates() => Ok(_rateService.GetRatesAsync().Result); // Fix: async all the way down, with cancellation public async Task<IActionResult> GetRates(CancellationToken ct) => Ok(await _rateService.GetRatesAsync(ct)); Why the AI wrote it: The assistant often writes a synchronous method first, then needs to call an async service from it. .Result is the shortest way to make it compile.
What happens in prod: In ASP.NET Core, the blocked call holds a thread-pool thread for the whole wait. One tester never notices. At 300 concurrent users the pool runs dry, the runtime adds threads only slowly, and response times jump from milliseconds to tens of seconds, even while the CPU sits idle. In classic ASP.NET or desktop apps it can deadlock outright because of the synchronization context. Its cousin async void is just as dangerous: an exception thrown inside it can crash the whole process instead of reaching your error handler.
Catch it in review: Search for .Result, .Wait(), .GetAwaiter().GetResult() and any async void that isn't an event handler. Check that CancellationToken flows from the action down to EF Core and HttpClient calls, so a cancelled request stops doing work instead of finishing a query nobody will read.
4. A new HttpClient per call
// AI-generated using var client = new HttpClient(); var json = await client.GetStringAsync(url); // Fix: register once and inject; add a timeout and resilience builder.Services.AddHttpClient<MarketDataClient>(c => { c.BaseAddress = new Uri(builder.Configuration["MarketData:BaseUrl"]!); c.Timeout = TimeSpan.FromSeconds(10); }) .AddStandardResilienceHandler(); // Microsoft.Extensions.Http.Resilience Why the AI wrote it: Wrapping an IDisposable in using looks like textbook good practice, and the assistant applies the rule mechanically.
What happens in prod: HttpClient is designed to be reused. Each disposed instance leaves its socket in TIME_WAIT for a while after closing. A busy service calling a market-data or payment API runs out of ephemeral ports, and every outbound call fails with a SocketException. Switching to one static client fixes the sockets but caches DNS forever, which breaks when the dependency fails over to a new IP. IHttpClientFactory handles both problems. The default 100-second timeout hurts too: one hung dependency ties up your request threads for nearly two minutes.
Catch it in review: Flag any new HttpClient() in application code. Check that every typed client sets an explicit timeout. Make sure retry policies suit the calls they wrap; never blindly retry a payment or another call that isn't safe to repeat.
5. Filtering in memory instead of in the database
// AI-generated: pulls the whole table, then filters var open = _db.Trades.ToList().Where(t => t.Status == "Open").Take(50); // Fix: let SQL do the work var open = await _db.Trades .AsNoTracking() .Where(t => t.Status == "Open") .OrderByDescending(t => t.CreatedAt) .Take(50) .ToListAsync(ct); Why the AI wrote it: ToList() is the classic "fix" for LINQ translation errors. When EF Core can't translate an expression, such as a custom C# method inside Where, the quickest workaround is to load everything and filter in memory. The code compiles and the error goes away.
What happens in prod: The dev database has 200 trades; production has 5 million. Every request now pulls the whole table over the network, tracks every entity, then throws away all but 50 rows. The result is slow pages, memory spikes, garbage-collection pauses and eventually timeouts or an OutOfMemoryException. The database also does far more I/O than it needs to, which slows every other query on the server.
Catch it in review: Look for ToList(), ToArray() or AsEnumerable() before Where, OrderBy or Take. Turn on EF Core's SQL logging in development and read the query it actually generates. Add AsNoTracking() to read-only queries, and always cap results with paging.
6. Swallowed exceptions
// AI-generated public async Task<Customer?> GetCustomerAsync(int id) { try { return await _db.Customers.FindAsync(id); } catch (Exception) { return null; } } // Fix: no blanket catch here; handle failures once, centrally public Task<Customer?> GetCustomerAsync(int id, CancellationToken ct) => _db.Customers.FirstOrDefaultAsync(c => c.Id == id, ct); // Program.cs: unhandled errors are logged and returned as ProblemDetails (500) builder.Services.AddProblemDetails(); app.UseExceptionHandler(); Why the AI wrote it: Assistants are tuned to hand back code that "doesn't crash". A blanket catch is the cheapest way to look robust.
What happens in prod: The database goes down, but the API returns 404 Not Found, because null means "no such customer". Nothing is logged as an error, so your alerts never fire. Support spends a day chasing "missing" customers who actually exist. When null can mean both "not found" and "broken", nobody can tell the two apart.
Catch it in review: Reject any catch (Exception) that neither rethrows nor logs. Allow catches only for specific exceptions the code can genuinely recover from, and let everything else reach one global handler.
7. N+1 queries
// AI-generated: 1 query for the clients, then 1 more per client var clients = await _db.Clients.ToListAsync(ct); foreach (var c in clients) { c.TotalExposure = await _db.Positions .Where(p => p.ClientId == c.Id) .SumAsync(p => p.Notional, ct); } // Fix: one query that aggregates in SQL var exposures = await _db.Clients .AsNoTracking() .Select(c => new ClientExposureDto( c.Id, c.Name, c.Positions.Sum(p => p.Notional))) .ToListAsync(ct); Why the AI wrote it: People describe the problem as a loop ("for each client, total their positions"), and the assistant translates the sentence literally.
What happens in prod: With 20 clients in dev that's 21 quick queries. With 4,000 clients in prod it's 4,001 round trips, and a dashboard that loaded in 80 ms now takes 40 seconds. Each round trip also pays network latency that localhost never had. Lazy-loaded navigation properties inside a loop cause the same problem, just hidden from view.
Catch it in review: Any await _db... inside a foreach is a red flag. In dev, log EF Core's SQL and count the queries per request. More than a handful for a single page usually means something is looping.
8. Over-posting (mass assignment)
// AI-generated: binds the request body straight onto the entity [HttpPut("{id}")] public async Task<IActionResult> UpdateUser(string id, User user, CancellationToken ct) { _db.Users.Update(user); await _db.SaveChangesAsync(ct); return NoContent(); } // Fix: accept only the fields the caller is allowed to change public record UpdateProfileRequest( [Required, MaxLength(100)] string DisplayName, [Phone] string? Phone); [Authorize] [HttpPut("me")] public async Task<IActionResult> UpdateProfile(UpdateProfileRequest req, CancellationToken ct) { var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); var user = await _db.Users.SingleAsync(u => u.Id == userId, ct); user.DisplayName = req.DisplayName; user.Phone = req.Phone; await _db.SaveChangesAsync(ct); return NoContent(); } Why the AI wrote it: Binding the entity directly is the shortest possible update endpoint, and plenty of scaffolding templates do exactly this.
What happens in prod: A user adds "isAdmin": true or "creditLimit": 1000000 to the JSON body, and EF Core saves it. Update() also marks every column as modified, so any field missing from the body is overwritten with its default value. That silently wipes data. The route id isn't even compared with the ID in the body.
Catch it in review: Request models should be dedicated DTOs or records with validation attributes, never EF entity types. Load the existing record, map the allowed fields explicitly, and then save.
9. A scoped service captured by a singleton
// AI-generated: a "cache" registered as a singleton that holds a DbContext builder.Services.AddSingleton<RateCache>(); public class RateCache(AppDbContext db) { public Task<List<Rate>> GetAsync() => db.Rates.ToListAsync(); } // Fix: real caching, with a fresh scope (and DbContext) per load public class RateCache(IServiceScopeFactory scopes, IMemoryCache cache) { public Task<List<Rate>?> GetAsync(CancellationToken ct) => cache.GetOrCreateAsync("rates", async entry => { entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5); using var scope = scopes.CreateScope(); var db = scope.ServiceProvider.GetRequiredService<AppDbContext>(); return await db.Rates.AsNoTracking().ToListAsync(ct); }); } Why the AI wrote it: "Make it a singleton so it's fast" is a common instinct, and the assistant doesn't trace the lifetimes of what it injects.
What happens in prod: One DbContext is now shared by every request, and DbContext is not thread-safe. Under concurrent load you get InvalidOperationException: A second operation was started on this context instance. Its change tracker also grows forever, so memory climbs and stale data gets served. Here's the dev-vs-prod twist: ASP.NET Core validates scopes only when the environment is Development. If your tests or staging run under another name, nothing catches it before production.
Catch it in review: Check every AddSingleton and AddHostedService for scoped dependencies such as DbContext, repositories or per-request services. Then switch validation on everywhere:
builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; }); 10. Local time and culture-sensitive parsing
// AI-generated var cutoff = DateTime.Now.Date.AddHours(17); // "5 PM cutoff" var amount = decimal.Parse(row["Amount"]); // "1,234.56" var tradeDate = DateTime.Parse(row["TradeDate"]); // "03/04/2026" // Fix: explicit time zone, injected clock, invariant culture, exact formats var ist = TimeZoneInfo.FindSystemTimeZoneById("Asia/Kolkata"); var nowIst = TimeZoneInfo.ConvertTime(_time.GetUtcNow(), ist); // _time is a TimeProvider var cutoff = new DateTimeOffset(nowIst.Date.AddHours(17), ist.BaseUtcOffset); var amount = decimal.Parse(row["Amount"], NumberStyles.Number, CultureInfo.InvariantCulture); var tradeDate = DateTime.ParseExact(row["TradeDate"], "yyyy-MM-dd", CultureInfo.InvariantCulture); Why the AI wrote it: DateTime.Now and Parse are the first APIs anyone learns, and on your laptop the defaults happen to match what you expect.
What happens in prod: The container runs in UTC with a different culture. The 5 PM IST cutoff now fires at 10:30 PM IST, so trades booked after the real cutoff land on the wrong business day. 03/04/2026 means 3 April on an en-IN or en-GB machine and 4 March on en-US. On a server with de-DE culture, 1,234.56 throws a FormatException. Every one of these bugs passes tests written and run on a single developer machine.
Catch it in review: Search for DateTime.Now, DateTime.Today and any Parse or ToString without an IFormatProvider. The built-in analyzer rule CA1305 flags the missing culture argument for you. Inject TimeProvider (.NET 8+) so you can test cutoffs with a fake clock.
11. Secrets in config files and in logs
// AI-generated // appsettings.json: "Default": "Server=prod-sql;User Id=sa;Password=P@ssw0rd!" _logger.LogInformation("Calling payment API with key {ApiKey} for {@Request}", _apiKey, request); // Fix: secrets come from a vault; logs carry IDs only builder.Configuration.AddAzureKeyVault( new Uri(builder.Configuration["KeyVault:Uri"]!), new DefaultAzureCredential()); _logger.LogInformation("Calling payment API for order {OrderId}", request.OrderId); Why the AI wrote it: Your prompt included a real connection string or API key for context, and the assistant put it back where it "belongs". Logging the whole request with {@Request} looks like helpful debugging.
What happens in prod: The secret now lives in Git history for good, in every clone and every CI log. An sa login hands an attacker full control of the database server. Logging the whole request writes card numbers, tokens or personal data into a log store that many people can read, which is a compliance incident in its own right.
Catch it in review: Run secret scanning (GitHub secret scanning or gitleaks) on every push, and never paste production secrets into an AI prompt. Treat {@Object} destructuring of requests in logs as a review comment. If a secret was ever committed, rotate it; deleting the line isn't enough.
12. Fire-and-forget work inside a request
// AI-generated: "send the email in the background so the API is fast" [HttpPost] public async Task<IActionResult> PlaceOrder(OrderRequest req, CancellationToken ct) { var order = await _orders.CreateAsync(req, ct); _ = Task.Run(() => _email.SendConfirmationAsync(order.Id)); return Accepted(order.Id); } // Fix: hand the work to a queue that a BackgroundService drains var order = await _orders.CreateAsync(req, ct); await _queue.EnqueueAsync(new SendConfirmation(order.Id), ct); return Accepted(order.Id); Why the AI wrote it: Task.Run makes the endpoint return instantly, and the demo looks great.
What happens in prod: The task outlives the request, so any scoped services it uses, such as DbContext, may already be disposed, and it fails with ObjectDisposedException. Its exceptions go nowhere, so failed emails vanish without a trace. When the app restarts during a deployment or a scale-in, any in-flight work is simply lost.
Catch it in review: Flag Task.Run, _ = SomethingAsync() and un-awaited tasks in controllers. Background work belongs in a BackgroundService reading from a Channel<T>, or in a durable queue such as Azure Service Bus, RabbitMQ or Hangfire when it must survive restarts.
Why it works in dev but not in prod
Dev and prod are different machines with different data, users, permissions and config. AI-generated code is usually tested only against the first.
| Difference | In dev | In prod | What to check |
|---|---|---|---|
| Configuration | appsettings.Development.json has every value | An env variable is missing, so a setting is silently null | Validate options at startup |
| Data volume | Hundreds of rows | Millions of rows | Query plans, indexes, paging |
| Concurrency | One user, one request | Hundreds of parallel requests | Thread safety, async, service lifetimes |
| Permissions | You are admin locally | Least-privilege service account | File, DB and Key Vault access |
| OS and runtime | Windows laptop | Linux container | Case-sensitive paths, line endings |
| Time and culture | Your laptop's IST time zone | Server runs in UTC | DateTime.Now, date and decimal parsing |
| Network | localhost, no latency | TLS, proxies, firewalls, slow dependencies | Timeouts, retries, certificates |
The configuration row causes the most "it worked yesterday" incidents. Make the app refuse to start when config is wrong, instead of failing on the first real request:
builder.Services .AddOptions<MarketDataOptions>() .Bind(builder.Configuration.GetSection("MarketData")) .ValidateDataAnnotations(Source:https://dev.to/thedevankit/reviewing-ai-generated-cbefore-it-hits-production-3a06