我有foreach循环来检索列表项,如:
//Gets the all the records of the Employee,
var emps = (from n in db.TIMESHEETs
where n.Empid_ID == 123
select n);
//gets the number of the records , ex: no. of the records are 2.
int count = emps.Count();//ex: count = 2
//Timesheet model class contains all get and set properties as below
List<Timesheetmodel> list = new List<Timesheetmodel>();
objts.GetTimeSheetDetails = list;
if (emps.Count() > 0)
{
Timesheetmodel model=new Timesheetmodel()
foreach (Timesheet ts in emps)
{
//from model class //from Database "Timesheet" Table
model.PROJ_ID = ts.PROJ_ID;
model.SUN_HRS = ts.SUN_HRS;
model.MON_HRS = ts.MON_HRS;
model.TUE_HRS = ts.TUE_HRS;
model.WED_HRS = ts.WED_HRS;
model.THU_HRS = ts.THU_HRS;
model.FRI_HRS = ts.FRI_HRS;
model.SAT_HRS = ts.SAT_HRS;
objts.GetTimeSheetDetails.Add(model);
//HERE ADDING ONLY LAST RECORD OF THE TABLE. I WANT TO ADD ALL THE RECORDS OF THE TABLE BUT ONLY LAST RECORD IS ADDING TO THE LIST
}
return View("Timesheet", objts);// RETURNING ONLY LAST RECORD OF THE DATABASE TABLE
}
问题是当我从数据库中获取记录的值并添加到列表时,只有最后一条记录正在添加,但不是表的所有记录。
这是什么解决方案。请帮助我。
答案 0 :(得分:1)
在您的代码更改中
if (emps.Count() > 0)
{
Timesheetmodel model=new Timesheetmodel()
foreach (Timesheet ts in emps)
{
//from model class //from Database "Timesheet" Table
model.PROJ_ID = ts.PROJ_ID;
model.SUN_HRS = ts.SUN_HRS;
model.MON_HRS = ts.MON_HRS;
model.`enter code here`TUE_HRS = ts.TUE_HRS;
model.WED_HRS = ts.WED_HRS;
model.THU_HRS = ts.THU_HRS;
model.FRI_HRS = ts.FRI_HRS;
model.SAT_HRS = ts.SAT_HRS;
objts.GetTimeSheetDetails.Add(model);
//HERE ADDING ONLY LAST RECORD OF THE TABLE. I WANT TO ADD ALL THE RECORDS OF THE TABLE BUT ONLY LAST RECORD IS ADDING TO THE LIST
}
}
到
if (emps.Count() > 0)
{
foreach (Timesheet ts in emps)
{
Timesheetmodel model=new Timesheetmodel()
//from model class //from Database "Timesheet" Table
model.PROJ_ID = ts.PROJ_ID;
model.SUN_HRS = ts.SUN_HRS;
model.MON_HRS = ts.MON_HRS;
model.`enter code here`TUE_HRS = ts.TUE_HRS;
model.WED_HRS = ts.WED_HRS;
model.THU_HRS = ts.THU_HRS;
model.FRI_HRS = ts.FRI_HRS;
model.SAT_HRS = ts.SAT_HRS;
objts.GetTimeSheetDetails.Add(model);
//HERE ADDING ONLY LAST RECORD OF THE TABLE. I WANT TO ADD ALL THE RECORDS OF THE TABLE BUT ONLY LAST RECORD IS ADDING TO THE LIST
}
}
答案 1 :(得分:1)
你应该在foreach循环中从Timesheetmodel创建一个新实例,如下所示:
if (emps.Count() > 0)
{
foreach (Timesheet ts in emps)
{
Timesheetmodel model=new Timesheetmodel();
//from model class //from Database "Timesheet" Table
model.PROJ_ID = ts.PROJ_ID;
model.SUN_HRS = ts.SUN_HRS;
model.MON_HRS = ts.MON_HRS;
model.TUE_HRS = ts.TUE_HRS;
model.WED_HRS = ts.WED_HRS;
model.THU_HRS = ts.THU_HRS;
model.FRI_HRS = ts.FRI_HRS;
model.SAT_HRS = ts.SAT_HRS;
objts.GetTimeSheetDetails.Add(model);
}
}