Question

I'm trying to write a query to select using the DateTime. Year as a where parameter, but I'm receiving this error from nunit:

NHibernate.QueryException : could not resolve property: Register.Year of: Estudantino.Domain.Events

In class Events I've a property named Register as a DateTime type.

public virtual DateTime Registada { get; set; }

This is the method that is returning the error:

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

The variable year is of type int, that is been passed to the method.

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

Was it helpful?

Solution

You may need to use HQL here instead. Basically NHibernate does not know really what to do with year. I suspect you need to use the RegisterFunction to register a YEAR function.

Please read this article in its entirety to fully understand what it is you are trying to do.

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

OTHER TIPS

QueryOver does not resolve things like DateTime.Year.

Use LINQ instead:

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

In QueryOver, you can just say:

dateTimeColumn.YearPart() == 1999

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top