实体框架,按日期/周/月分组处理日期时间

时间:2016-06-15 07:30:22

标签: c# sql sql-server entity-framework datetime

正如标题所说,我的表格中有一个日期时间列。

我需要以三种方式将我的记录分组,分为三种不同的情况:

  1. 按天分组
  2. 按周分组
  3. 按月分组
  4. 如果可能的话,如何在实体框架中使用lambda表达式执行这3个不同的group by语句?

    更新:链接的问题重复,不是真正的重复。我要求lambda解决方案,它不在链接

3 个答案:

答案 0 :(得分:1)

您可以使用此方法:

'submit .login-form': function (event) {
        event.preventDefault();

        var emailVar = event.target.loginEmail.value;
        var passwordVar = event.target.loginPassword.value;

        Meteor.loginWithPassword(emailVar, passwordVar, function (err) {
            if (!err) {
                console.log("User logged in");

                Bert.alert({
                    title: "Welkom: " + Meteor.user().profile.name,
                    message: "You're logged in !",
                    type: 'success',
                    style: 'growl-top-right',
                    icon: 'fa-check'
                });
            } else{
                // Do something on error....
                console.log("Not logged in, and error occurred:", err);  // Outputs error
            }

        });
    }

答案 1 :(得分:0)

使用此

List<MyEntitiy> list = (from e in Context.MyEntities group e by e.Date.Day into g select g).ToList();

对于月份,将e.Date.Day替换为e.Date.Month

对于,您必须先计算WeekOfYear

public int GetWeekOfYear(this DateTime d)
{
    GregorianCalendar c = new  GregorianCalendar();
    return c.GetWeekOfYear(d,CalenderWeekRule.FirstDay,DayOfWeek.Sunday);
}

并使用

List<MyEntitiy> list = (from e in Context.MyEntities group e by e.Date.GetWeekOfYear() into g select g).ToList();

答案 2 :(得分:0)

您可以使用linq和lambda表达式

使用以下格式

按日分组

    var results = from p in db.table
                          group p.data by p.DateTime.UtcNow.Day into g
                          select new { Id = g.Key, parameters = g };

按周分组

    var result = from p in db.table
                         group p.data by p.DateTime.UtcNow.DayOfWeek into g
                          select new { Id = g.Key, parameters = g}

或者

    //get the 7days of the week by the below method and perform between operation
    DateTime fromDate = DateTime.Today.Subtract(new TimeSpan(7, 0, 0, 0));
    DateTime today = DateTime.Today;
    var result = from p in db.table
                         group p.data by (DbFunctions.TruncateTime(today) && DbFunctions.TruncateTime(today) >= DbFunctions.TruncateTime(fromDate)) into g
                         select new { Id = g.Key, parameters = g}

同样适用于月份

    DateTime fromDate = DateTime.Today.Subtract(new TimeSpan(30, 0, 0, 0));
    DateTime today = DateTime.Today;
    var result = from p in db.table
                         group p.data by (DbFunctions.TruncateTime(today) && DbFunctions.TruncateTime(today) >= DbFunctions.TruncateTime(fromDate)) into g
                         select new { Id = g.Key, parameters = g}