【问题标题】:Entity Framework Linq Entity convert to CustomModelEntity Framework Linq Entity 转换为 CustomModel
【发布时间】:2014-06-24 00:06:05
【问题描述】:

我对实体有以下 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);
    }

【问题讨论】:

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


    【解决方案1】:

    你可以做类似的事情

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

    抱歉,我的手机回答的格式不佳。

    【讨论】:

    • 那行不通,因为在某些时候我需要做: .ToString(@"hh\:mm");在 Linq 语句中会出现错误。
    • 查看这篇文章forums.asp.net/t/…
    猜你喜欢
    • 2019-09-02
    • 1970-01-01
    • 2015-12-12
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多