Querying with nHibernate where todays date is between publishDate and Expiry date
Asked Answered
T

2

9

I am trying to figure out how to best query in NHibernate so that the returned results are between for entries where todays time is >= PublishDateTime and <=ExpiryDateTime

The expiry date can be null so I need to allow for that. I found a couple of examples here and here but they seem to work in a different way and accept 2 values and compare to one DB field. I want the other way wrong really.

Query so far:

var query = _session.CreateCriteria<Message>()
                .AddOrder(Order.Desc("PublishedDateTime"))
                .List<Message>();
                return query;

Any suggestions would be greatly received!

Tramway answered 6/12, 2010 at 16:29 Comment(0)
A
16

Easiest Linq query:

return _session.Query<Message>()
               .Where(m => DateTime.Today >= m.PublishDateTime &&
                          (m.ExpiryDateTime == null ||
                           DateTime.Now <= m.ExpiryDateTime)
               .OrderByDescending(m => m.PublishDateTime)
               .ToList();

Criteria:

return _session.CreateCriteria<Message>()
               .Add(Restrictions.Le("PublishedDateTime", DateTime.Today) & 
                                    (Restrictions.IsNull("ExpiryDateTime") |
                                     Restrictions.Ge("ExpiryDateTime",
                                                     DateTime.Now)))
               .AddOrder(Order.Desc("PublishedDateTime"))
               .List<Message>();
Alkalinize answered 6/12, 2010 at 20:2 Comment(4)
+1 thanks for giving both examples. Linq I new but was interested in the Criteria method so thank youTramway
Do me a favour just change .Today to .Now and I'll mark you as the answer. Thanks again for your input :)Tramway
I thought you wanted "today's date", not "current time" (that's what the question says)Alkalinize
sorry meant date time - I've mislead with worded but worded correctly on the fields - will update now - thanks again for your helpTramway
P
0

In c# :

          var formato = "dd/MM/yyyy h:mm:ss";
            var sDesde = DateTime.Now.ToString("dd/MM/yyyy") + " 0:00:00";
            var sHasta = DateTime.Now.ToString("dd/MM/yyyy h:mm:ss");

            Viaje vDesde = new Viaje { Viajefecha = DateTime.ParseExact(sDesde, formato , null) };
            Viaje vHasta = new Viaje { Viajefecha = DateTime.ParseExact(sHasta, formato, null) };

            StringWriter strWriter = new StringWriter();
            var resultado = cp.sesion.CreateCriteria<Viaje>().Add(Expression.Between("Viajefecha", vDesde.Viajefecha, vHasta.Viajefecha)).AddOrder(Order.Asc("Viajefecha")).List<Viaje>();
Piranesi answered 7/1, 2016 at 7:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.