问题
I want to use a stored procedure for DB query, it works for a single query, but in loop, it executes like in first loop iteration.
var getAutoResults = new List<List<Karat_getAutoData_Result>>();
foreach (var elem in meas)
{
getAutoResults.Add(await _context.KaratGetAutoDataResults
.FromSql($"dbo.Karat_getAutoData @MeasurementId = {elem.MeasurementId}, @CalcRequestId = {null}")
.ToListAsync());
}
After this I get N times the same results, but all ids are different.
回答1:
I can resolve it only like this. I'm just creating new context instance in each loop. I think this is bad idea, but it works.
var getAutoResults = new List<List<Karat_getAutoData_Result>>();
var optionsBuilder = new DbContextOptionsBuilder<TestRecipesDBContext>();
optionsBuilder.UseSqlServer("MY CONNECTION STRING");
foreach (var elem in meas)
{
using (var localContext = new TestRecipesDBContext(optionsBuilder.Options))
{
getAutoResults.Add(await localContext.KaratGetAutoDataResults
.FromSql($"dbo.Karat_getAutoData @MeasurementId={elem.MeasurementId},@CalcRequestId={null}")
.ToListAsync());
}
}
Solution below more usefull, just need use AsNoTracking():
getAutoResults.Add(await localContext.KaratGetAutoDataResults
.FromSql($"dbo.Karat_getAutoData @MeasurementId=elem.MeasurementId},@CalcRequestId={null}")
.AsNoTracking()
.ToListAsync());
来源:https://stackoverflow.com/questions/51207538/asp-net-core-stored-procedure-not-working-in-loop