实体框架Linq实体转换为CustomModel

时间:2014-06-23 14:32:16

标签: entity-framework entity-framework-4 linq-to-entities linq-to-objects

我有以下linq到实体:

  var dbShifts = DbContext.Set < SetupShift > ()
      .AsNoTracking()
      .Where(s => s.ShiftCode == shiftCode).ToList();

Entity SetupShift具有以下属性:

public class SetupShift
    {
        public int ShiftId { get; set; }
        public string ShiftCode { get; set; }
        public byte Day { get; set; }
        public TimeSpan InTime { get; set; }
        public TimeSpan OutTime { get; set; }
        public int WorkHours { get; set; }
        public TimeSpan LunchOut { get; set; }
        public TimeSpan LunchIn { get; set; }
        public bool IsActive { get; set; }
        public string CategoryType { get; set; }
    }

现在,我需要将其包装到自定义模型ShiftModel

 public class ShiftModel
    {
        public int ShiftId { get; set; }
        public string ShiftCode { get; set; }
        public byte Day { get; set; }
        public string DayName { get; set; }
        public string InTime { get; set; }
        public string OutTime { get; set; }
        public int WorkHours { get; set; }
        public string LunchOut { get; set; }
        public string LunchIn { get; set; }
        public bool IsActive { get; set; }
        public string CategoryType { get; set; }
    }

EF实体模型与我的ShiftModel之间的唯一区别是自定义模型中的TimeSpan属性为String

我想知道是否有一种快速的方法从我的实体数据生成我的ShiftModel而不是循环每个实体:

List<ShiftModel> shifts = new List<ShiftModel>();

foreach(var entity in SetupShift){
       ....
       newShiftModel = new ShiftModel();
       newShiftModel.InTime = new TimeSpan(0, 0, 0).ToString(@"hh\:mm");
       ....
       ....
       shifts.Add(newShiftModel);
    }

1 个答案:

答案 0 :(得分:0)

您可以执行类似

的操作
var dbShifts = DbContext.Set < SetupShift > () .AsNoTracking() .Where(s => s.ShiftCode == shiftCode).Select(x => new ShiftModel() { 
 ShiftId = x.ShiftId, 
 ShiftCode = x.ShiftCode, 
Etc..... 
}).ToList();

对于从我的手机接听此格式不佳的格式抱歉道歉。