ASP.NET Core stored procedure not working in loop

寵の児 提交于 2021-02-10 08:14:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!