I have a web app using code-first EF Core.
One of the controllers needs to run what should be a simple query (basically SELECT TOP 1 * FROM companies WHERE id = @id; in EF terms,
var data = await _context.FindAsync<Company>(id)).
The first time it runs that request per HTTP request takes upwards of 3 seconds; subsequent calls on the same _context - even to get the same company - typically return in times like 0.0000040 seconds. Occasionally, however, a subsequent call to get a company will take multiple full seconds again.
Similar results are happening on other controllers, which makes me think this is a global configuration issue of some sort.
The company table has several NVARCHAR(MAX) columns, which some sources indicate might be less than ideal, but the model has no referenced models (ie., EF Core doesn't need to do any joins to build a company model).
I've tried bumping the EF Core and SQL NuGet packages (Microsoft.Data.SqlClient is at 6.13; all of the EntityFrameworkCore packages I'm using are at 8.0.22), as well as setting the app context switches recommended here; namely:
AppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.UseCompatibilityAsyncBehaviour", false);
AppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.UseCompatibilityProcessSni", false);
As suggested in that same link, I've tried switching to the sync calls, as well. Further, I've added and (I believe) registered an optimized DB context (Optimize-DbContext in the package manager console), plus registering it via
return services.AddDbContext<AppDbContext>
(options =>
options.UseSqlServer(connectionString!)
.UseModel(AppDbContextModel.Instance));
Nothing I've tried has had any meaningful impact on that initial query's runtime. What am I missing?
SELECT * FROM companiesin SSMS does take 11 seconds to run; the whole result set copy-pasted into a text file, is just under 1 MB. Getting just the one company in SSMS takes less than a second.