Question

I need to use this SQL string in different database context, I know it work in MSSQLCE4 but it won't work in MySql

sql = session.CreateSQLQuery(
    "SELECT DISTINCT DATEPART(yyyy," + DataRicezioneFile + ") AS Data" +
    " FROM " + Ricevuta + 
    " ORDER BY Data DESC"
);

So I have written the same in Nhibernate using QueryOver

list = session.QueryOver<Ricevuta>()
       .Select(
           Projections.Distinct(Projections.SqlFunction( "year", NHibernateUtil.Int32,
           Projections.Property<Ricevuta>( r => r.DataRicezioneFile )
       )))
       .OrderBy(r=>r.DataRicezioneFile).Desc
       .List<int>().ToList();

Now this work in MySql but not in MSSQLCE4, I suppose because of the use of YEAR(DateTime) instead of DATEPART(yyyy,DateTime)

I can't find out how to let the function work independent from the database engine. Any idea?

Was it helpful?

Solution 2

Well, thanks to the suggestion of @Sebin to use Nhibernate Linq I've found that this is working in both my test case and hopefully in many others

List<DateTime> tmpList = session.Query<Ricevuta>()
                             .Select( x => x.DataRicezioneFile )
                             .Distinct()
                             .ToList();

list = tmpList.OrderByDescending(x=>x.Year)
                             .Select(x=>x.Year)
                             .Distinct()
                             .ToList<int>();

For a complete answer, is it possible to do the same with a full linq query as this:

var query = from ric in session.Query<Ricevuta>()
            select ric.DataRicezioneFile;
List<DateTime> tmpList= query.ToList();
list = tmplist.OrderByDescending( x => x.Year ).Select( x => x.Year ).Distinct().ToList<int>();

In both case is necessary to use a tmpList of DateTime because using a direct DateTime.Year request is not working the same on different DBM.

OTHER TIPS

Can you try Nhibernate Linq ?

Because i had done these kind of string manipulations and date manipulation using Nhibernate Linq

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