如何在查询生成的列表中添加项目

时间:2019-02-01 08:01:08

标签: c# .net asp.net-mvc entity-framework

这是我的清单,我想在其中添加一个额外的记录................................. ..............

var foremandata = (from f in db.mqTimeReportingTimeLogs
                               join e in db.mqEmployeeMasters on f.tlEmployeeId equals e.empId
                               join c in db.mqCraftCodeMasters on f.tlCraftId equals c.craftCodeId
                               where f.tlJobId == jobid && f.tlCompanyId == compId && f.tlWeekEnding == weekend

                               select new
                               {
                                   EmpNum = e.empnum,
                                   EmployeeName = e.empName,
                                   DateWorked = f.tlDateWorked,
                                   CraftCode = c.craftCode,
                                   CCID = f.tlCraftId,
                                   STime = f.tlStraightTime,
                                   OTime = f.tlOT
                               }).OrderBy(x => x.EmployeeName).ToList();

1 个答案:

答案 0 :(得分:0)

建议您不要构建匿名类型,而应构建一个强类型的DTO类,该类包含查询结果投影的所有必需属性。下面是DTO类的示例:

public class EmployeeDTO
{
    public int EmpNum { get; set; }
    public string EmployeeName { get; set; }
    public DateTime DateWorked { get; set; }
    public string CraftCode { get; set; }
    public int CCID { get; set; }
    public DateTime STime { get; set; }
    public DateTime OTime { get; set; }
}

然后您可以将该类用作查询的投影目标:

var foremandata = (from f in db.mqTimeReportingTimeLogs
                   join e in db.mqEmployeeMasters on f.tlEmployeeId equals e.empId
                   join c in db.mqCraftCodeMasters on f.tlCraftId equals c.craftCodeId
                   where f.tlJobId == jobid && f.tlCompanyId == compId && f.tlWeekEnding == weekend

                   select new EmployeeDTO
                   {
                        EmpNum = e.empnum,
                        EmployeeName = e.empName,
                        DateWorked = f.tlDateWorked,
                        CraftCode = c.craftCode,
                        CCID = f.tlCraftId,
                        STime = f.tlStraightTime,
                        OTime = f.tlOT
                   }).OrderBy(x => x.EmployeeName).ToList(); // returns List<EmployeeDTO>

然后,您可以使用DTO类使用Add()AddRange()方法添加新项,具体取决于要添加的内容(单个数据还是List<EmployeeDTO>):

foremandata.Add(new EmployeeDTO()
{
    EmpNum = 1, // some value
    EmpName = "[employee name]",

    // other properties here
});