How to execute stored procedure in foreach loop using EF Core in .NET Core?

entity-framework-core stored-procedures

Question

I am trying to execute a stored procedure in a foreach loop as follows:

foreach (var p in results)
{
    string InputOne = year.ToString();
    char c = '0';
    string InputTwo = month.ToString().PadLeft(2, c); 

    List<Entity> data = new List<Entity>();

    SqlParameter Param1 = new SqlParameter("@Param1", "Month");
    SqlParameter Param2 = new SqlParameter("@Param2", p.Id);
    SqlParameter Param3 = new SqlParameter("@Param3", InputOne);
    SqlParameter Param4 = new SqlParameter("@Param4", InputTwo);

    string usp = "Schema.usp_spname @Param1, @Param2, @Param3, @Param4";
    data = _dbContext._sp_GetEmployeeAttendanceData.FromSql(usp, Param1, Param2, Param3, Param4).ToList();
}

I am getting the same data for all conditions while my database contains different data..

Please help me to solve this!

1
1
3/1/2019 11:35:39 AM

Popular Answer

the last line in your loop

data =

is replacing the data variable in each iteration, so you will only ever get the last iteration in that For Loop.. You need to change it so that the (data =) part appends to a list instead.. If data is a list, you can use data.AddRange()

And this line List<Entity> data = new List<Entity>(); needs to be moved outside of the loop

0
3/1/2019 1:48:33 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow