C# NHibernate Simple Question

2019-07-18 02:21发布

问题:

I'm using NHibernate-driven repository, Fluent mappings and attempt to use Linq to NHibernate.

But for some simple query like this

Retrieve<XValue>(x => (x.Timestamp.CompareTo(start) >= 0 &&
                       x.Timestamp.CompareTo(end) <= 0 ));

// 'Retrieve' here acts simply as 'session.Query<T>().Where(expression);'

I get the following result:

System.NotSupportedException: Int32 CompareTo(System.DateTime)

I don't know why, but CompareTo operations aren't projected to the database and the output is also kind of weird:

create table "QuotUnitDescriptor" (
    Id  integer,
   PaperId INTEGER,
   Timestamp DATETIME,
   InPaperIdx INTEGER,
   primary key (Id)
)

NHibernate: INSERT INTO "QuotUnitDescriptor" ......................

// Many INSERT's

NHibernate: select cast(count(*) as INTEGER) as col_0_0_ 
    from "QuotUnitDescriptor" binaryunit0_

I can't understand why this operation invokes a select -> integer operation.

How should the following date-oriented query be implemented? (using Linq is better, but criterias are also fine, I think).

回答1:

NHibernate.Linq provider is unable to transform CompareTo call to sql.

Use something like:

Retrieve<XValue>(x => x.Timestamp>start && x.Timestamp<end);

P.s. and avoid repositories. That's a naive abstraction.