Querying with nHibernate where todays date is between publishDate and Expiry date

早过忘川 提交于 2019-12-09 11:29:32

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/4368623/querying-with-nhibernate-where-todays-date-is-between-publishdate-and-expiry-dat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!