GroupBy does not work as expected when I compute a new date. The usage is to make group of entities by month.

How could I do this?

Entity:

  [HierarchyRoot]
  public class MyEntity : Entity
  {
    [Field, Key]
    public int Id { get; private set; }

    [Field]
    public DateTime Date { get; set; }
  }

  for (int i = 0; i < 100; i++)
  {
    new MyEntity(session) { Date = DateTime.Now.AddMinutes(-1.0 * i) };
  }

Query

  var query = from e in session.Query.All<MyEntity>()
              let yearmonth = new DateTime(e.Date.Year, e.Date.Month, 1)
              group e by yearmonth into g
              select g;

  Console.WriteLine(query.Count());

Result 100

Only one group was expected.

asked Feb 15 '12 at 03:51

olorin's gravatar image

olorin
356818489


One Answer:

Greetings olorin,

Could you try the following one?

var query = from e in session.Query.All<MyEntity>()
          let yearmonth = e.Date.Year*100 +  e.Date.Month
          group e by yearmonth into g
          select g;

answered Feb 15 '12 at 07:05

Dmitri%20Maximov's gravatar image

Dmitri Maximov
22111211

edited Feb 15 '12 at 07:06

This should work, but this may be better:

var query2 = from e in session.Query.All<MyEntity>()
         let yearmonth = new { Year = e.Date.Year, Month = e.Date.Month }
         group e by yearmonth into g
         select g;

Is this behavior easy to change for you? I can change the DateTime type to a custom type but this would need some work to adapt the rest of our application.

(Feb 15 '12 at 08:26) olorin olorin's gravatar image

Right, your case is much cleaner.

Unfortunately, I can't provide you with the exact timeframe, we are in the middle of a development sprint right now and it is expected to be closed at the end of February. But I can promise that if we get some spare time, we will take a look at the issue.

(Feb 15 '12 at 08:49) Dmitri Maximov Dmitri%20Maximov's gravatar image
Your answer
Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!
toggle preview

powered by OSQA