简体   繁体   中英

C# strange lambda behavior

Could someone point out why this could be happening:

I am using NHibernate and the Linq provider for it.

The code that fails is listed here:

var sequence = session.Query<T>();

var wtfSequence = sequence.Where(x => true);
var okaySequence = sequence.Where(x => x.Id > 0);

Debugging shows that sequence (which is an IQueryable<T> ) after this contains 2 elements, which were added to the database.

I expect the first Where statement to yield all elements from that sequence, but unfortunately it leaves 0 elements.

(WHY???)

The second Where statement, on the contrary, actually yields 2 elements as it should work.

Here are the NHibernate -> Sqlite queries for the first and second Where statements.

NHibernate: select cast(count(*) as INTEGER) as col_0_0_ from "BinaryUnitProxy_IndicatorUnitDescriptor" binaryunit0_ where @p0='true';@p0 = 'True' [Type: String (0)]

NHibernate: select cast(count(*) as INTEGER) as col_0_0_ from "BinaryUnitProxy_IndicatorUnitDescriptor" binaryunit0_ where binaryunit0_.Id>@p0;@p0 = 0 [Type: Int32 (0)]

Now, if I test the same code with my InMemoryRepository , which stores every entity in a simple list, the (x => true) works absolutelty fine.

So - why does this happen when using NHibernate ? Is this a bug or I am doing something wrong?

Thank you.

I don't know NHibernate, but the problem is obvious from the generated SQL: Your database does not consider true (lowercase t) equal to True (uppercase T). In SQL server you can change this by modifying the database collation (which is a really bad idea unless you want case insensitivity for other reasons).

My guess is this is a bug in NHibernate that you need to work around. Test t => 1 == 1 instead of t => true , which might work depending on how the NHibernate code is written.

My guess is that this is a bug in NHibernate based on the SqLite output that you show. You could try X => X.Id == X.Id rather than X => true and see if that works.

Looks like a bug to me. Its converting a boolean operation to a string evaluation, and even that's screwed up, as it sets up the query with true and evaluates using True , so a case-sensitive test would fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM