【问题标题】:LINQ query always return NullLINQ 查询总是返回 Null
【发布时间】:2021-02-19 11:32:30
【问题描述】:

我是 LINQ 的新手,但遇到了问题。

我在两个不同的 dbContext(userContext 和 mailContext)中有两个表。在将此数据添加到 UserMail 表后,我想从 UserAccount 表中选择一部分数据。 UserAccount 表有很多列,而 UserMail 表有 4 列(CreatedDate、UserAccountId、UserType、ItemCount)

选择代码:

 var selectedUsers = _userContext.UserAccount
        .Where(x=>x.Created == new DateTime(2021, 02, 17))
        .Select(x => new UserMail()
        {
            CreatedDate = x.Created,
            UserAccountId = x.AccountId,
            UserType = x.UserType,
            ItemCount = (int?)x.ItemCount,
        }).ToList();

查询返回 null,selectedUsers 的计数=0。我从 SQL 中检查,一些数据退出,我错过了查询中的一点吗?

实际上,我需要按 AccountId 和 CreatedDate 分组的 ItemCount 的总和,但首先,我想得到这个查询的结果。

【问题讨论】:

    标签: linq sql-to-linq-conversion


    【解决方案1】:

    这意味着您不能满足where 条件,因为很可能小时/分钟/秒部分彼此不相等。下面的呢?

    var selectedUsers = _userContext.UserAccount
            .Where(x=>x.Created.Date == new DateTime(2021, 02, 17).Date)
            // new DateTime(2021, 02, 17) could be used simply but the default
            // behavior may be changed in future.
            .Select(x => new UserMail()
            {
                CreatedDate = x.Created,
                UserAccountId = x.AccountId,
                UserType = x.UserType,
                ItemCount = (int?)x.ItemCount,
            }).ToList();
    

    【讨论】:

    • 我尝试了您的解决方案,但它不起作用。当我删除 where 子句时,它正在工作。在数据库中,日期格式为 2021-02-17 11:30:35.113。如何在 where 子句中转换这个 2021-02-17?
    • _userContext.UserAccount[0].Created 的输出是 2021-01-15 16:23:18.210
    • oov,我很抱歉,我没有看到等式两边的 .Date。再次感谢,它有效。
    猜你喜欢
    • 2021-01-15
    • 2018-09-18
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    相关资源
    最近更新 更多