linqsql-to-linq-conversion

LINQ query always return Null


I am new in LINQ and I have a problem.

I have two tables in two different dbContext(userContext and mailContext). I want to select a part of data from UserAccount table, after I add this data to UserMail table. UserAccount table have lots of columns and UserMail tables have 4 columns (CreatedDate, UserAccountId, UserType, ItemCount)

The selection code:

 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();

The query return null, The count of selectedUsers=0. I check from SQL, some data exits, am I miss a point in the query?

Actually, I need the sum of ItemCount grouped by AccountId and CreatedDate but first of all, I want to get the result of this query.


Solution

  • It means you can't satisfy the where condition since highly likely hours/minutes/seconds parts are not equal each other. What about the following?

    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();