【问题标题】:How to count number of columns having a certain values using Entity Framework如何使用实体框架计算具有特定值的列数
【发布时间】:2018-07-12 13:41:25
【问题描述】:

我在数据库中有一个员工考勤表,其中包含以下列:

ID | Date | EmployeeId | Day1 | Day2 | Day3.... | Day31

1  | .... | ...........| 1    |  1   |  1 ..... | 5

Day1 到 Day31 具有从 1 到 5 的整数值,每个都有特定的含义。假设我们在 Day1 到 Day28 的列下有 1 个,在 Day29 到 Day31 的列下有 5 个,这里我们有 28 个 1 和 3 个针对 ID 1 的 5。

待办事项

我想计算一个特定的 ID,即有多少列的值为 1,有多少列的值为 2,多少列的值为 3,多少列的值为 4,多少列的值为 5。(使用实体框架)

示例代码:

public class LeaveBalance
{
        public int ShortLeave { get; set; }
        public int HalfLeave { get; set; }
        public int FullLeaves { get; set; }
        public int Absent { get; set; }
        public Guid EmpCode { get; set; }
        public Employee Employee { get; set; }
        public int TotalLeaves { get; set; }              
}

我数数有困难:

public List<LeaveBalance> ReturnCount(DateTime date)
{
    List<LeaveBalance> count = new List<LeaveBalance>();

    using (var _db = new AppDbContext())
    {
        var employee = _db.EmployeeAttendanceSheets
                          .Where(r => r.Date.Month == date.Date.Month && r.Date.Year == date.Date.Year)
                          .ToList();

        foreach (var emp in employee)
        {
            count.Add(new LeaveBalance { Absent = })
        }
    }

    return count;
}

请提前帮助和感谢

【问题讨论】:

    标签: sql-server entity-framework linq-to-sql


    【解决方案1】:
    var item = context.Table.Find(id);
    var data = item.GetType().GetProperties().Where(x => x.Name.Contains("Day"))
                   .Select(x => (int)x.GetValue(item)).ToList();
    var answer = Enumerable.Range(1, 5)
                 .Select(x => new { number = x, count = data.Count(y => y == x) }).ToList();
    

    【讨论】:

    • 非常感谢你,它就像一个魅力,你拯救了我的一天
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多