NHibernate 3 - QueryOver with DateTime

I am trying to write a query for selection using DateTime. Year as a where parameter, but I get this error from nunit:

NHibernate.QueryException: Failed to resolve property: Register.Year of: Estudantino.Domain.Events

In the Events class, I have a property named Register as a DateTime type.

public virtual DateTime Registada { get; set; } 

This is the method returning the error:

  using (ISession session = NHibernateHelper.OpenSession()) { return session.QueryOver<Evento>() .Where(x => x.Register.Year == year) .List(); } 

This variable year is of type int , which was passed to the method.

Does anyone have an idea of ​​what I'm doing wrong? My database server is SQL Server 2005 Express.

+4
source share
4 answers

Instead, you may need to use HQL. Basically, NHibernate does not know what to do with year . I suspect you need to use RegisterFunction to register the year function.

Read this article in its entirety to fully understand what exactly you are trying to do.

  • Creating a custom dialect in code
  • Create a function on the SQL server called MyYearFunction that returns the year for the date
  • Then use HQL (not sure if QueryOver can do this) to get the date where dbo.MyYearFunction(:date) = 12" ...
+3
source

QueryOver does not allow things like DateTime.Year .

Use LINQ instead:

 return session.Query<Evento>() .Where(x => x.Register.Year == year) .ToList(); 
+7
source

In QueryOver, you can simply say:

 dateTimeColumn.YearPart() == 1999 

There are also other extension methods: MonthPart() , DayPart() , etc.

+5
source

.Where (x => x.Register> = new DateTime (year, 1, 1) & x.Register <new DateTime (year + 1, 1, 1))

-1
source

Source: https://habr.com/ru/post/1336649/


All Articles