I have the following function which returns a Model
. It is taking time say if there are 2000 employees
, it takes 3-4 minutes to return data
. I actually want to optimize this function
. I have done few things which are included in the below code, but still it takes lots of time.
using (var ctx = new ApplicationDbContext(schemaName))
{
List<Employee> list = new List<Employee>();
Employee mod = new Employee();
var data = ctx.Employee.Where(a => a.Company == comp && a.Status == Live)
.Select(a => new
{
Id = a.Id,
Code = a.Code,
FName = a.FName,
DateOfJoining = a.DateOfJoining,
Category = a.Category,
Department = a.Department,
Designation = a.Designation;
})
.ToList();
var loadValues = ctx.CValue.Where(c => c.Company == comp).ToList();
foreach (var item in data)
{
mod = new Employee();
mod.Id = item.Id;
mod.Code = item.Code;
mod.FName = item.FName;
mod.DateOfJoining = item.DateOfJoining;
mod.Category = item.Category;
mod.Designation = item.Designation;
mod.Department = item.Department;
int designation = (item.Designation == null) ? 0 : item.Designation;
int department = (item.Department == null) ? 0 : item.Department;
if (designation != 0)
mod.DesignationString = loadValues.Where(c => c.CompanyId == comp && c.Id == designation).Select(c => c.ComboValue).FirstOrDefault();
if (department != 0)
mod.DepartmentString = loadValues.Where(c => c.Company == comp && c.Id == department).Select(c => c.ComboValue).FirstOrDefault();
list.Add(mod);
}
return list;
}
}
I think it is the foreach
loop which is taking time. Any workaround for this?How to optimize the above Code?