1

I have sql database that has a DateTime field. When I query with LINQ to Object I get a date in one format "20/01/2022 12:00:00 AM", but if SelectMany (LINQ to Entinty) get a different format "Jan 20 2021 12:00AM".

The desired output is the flat data structure that is acheived by the foreach after a select query or SelectMany query.

Why do i get differnt output from same data and what is a good way to make consisent depending on using SelectMany or Select.

How can I fix this to get the same format in one place?

Which method is better? Not use SelectMany?

Here is the code:

 var a = db.Tasks.Include("Actions.ProgressUpdate.State")
      .Where(p => p.ProjectId == ProjectId && p.Actions.Count>0)
      .ToList();

 var b = db.Tasks.Include("Actions.ProgressUpdate.State")
      .Where(p => p.ProjectId == ProjectId && p.Actions.Count>0);

 //object list gives date as "20/01/2022 12:00:00 AM"
 var objectList = new List<dynamic>();
      foreach (var item in a)
      {
            foreach (var action in item.Actions)
            {
                aList.Add(new
                {
                    TaskId = item.Id,
                    date = action.CurrentDueDate.ToString()                       
                });
            }
       }

 //entinty gives date as "Dec  9 2021  4:31PM"
 var entityList = b
      .SelectMany(p => p.Actions,
      (parent, child) => new
      {
            TaskId = parent.Id,
            date = child.CurrentDueDate.ToString()                
      });  
Matt Watson
  • 251
  • 2
  • 6
  • 2
    This has nothing directly to do with `SelectMany`. First one uses .Net's formatting, second uses some custom string concatenation. Why should they be the same? You could change the second one to use the [`FORMAT` function](https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql?view=sql-server-ver15) (utilizing [this answer](https://stackoverflow.com/a/53949705/14868997)) the use it like this `SqlFunctions.Format(child.CurrentDueDate, "d", "es-ES")` – Charlieface Dec 15 '21 at 00:21
  • Think my code to flatten confuses the issue. Same data (from data base) and use different way to make the list and subsequently convert to string gives different result. How can I make the ouput the same? Where is the decision made on how the date is converted to string? One can use the SQLfunction (the selectmay) and one cannot. – Matt Watson Dec 15 '21 at 06:34
  • The first is executed in C#, the second by SQL Server. As I said, you could use the SQL `FORMAT` function – Charlieface Dec 15 '21 at 11:30

0 Answers0