Using .Any() in combination with NHibernate and inheritance

Description

Hi,

I'm using NHibernat in combination with inheritance. That means I have a Parent and a Child object that inherit from each other, but that each have their own mapping file, so seperate tables are created.

I was having issues with the .Any() functionality when I do the following:

var value = session.Query<ParentObject>().Any(t => t.Name.Equals(name));

I've been debugging the NHibernate source code and I found out that when a Query i performed on an object, it also loops through all other class that inherit from it. This means that for an .Any function call, a result set of booleans is filled. But the strange thing is that in DefaultQueryProvider.cs (line 125) the following happens: return results[0];

The first result is the .Any result of my ChildObject, so the result from my ParentObject is completely ignored.

I made a UnitTest to prove this behavior:

[TestMethod] public void TestInheritance() { var name = "test"; var sessionFactory = CreateSessionFactory(database2); using (var session = sessionFactory.OpenSession()) using (var transaction = session.BeginTransaction()) { var testObject = new ParentObject(); testObject.SetName(name); session.SaveOrUpdate(testObject); transaction.Commit(); var value = session.Query<ParentObject>().Any(t => t.Name.Equals(name)); Assert.IsTrue(value); } }

You would not expect this, but this unit test fails. If I test the same code with a class that doesn't have other classes inherit from it, the unit test passes.

I can make a workaround for this by using:

var value = session.Query<ParentObject>().FirstOrDefault(t => t.Name.Equals(name)) != null

but I just want to use the Any() functionality.

Does anyone maybe have a solution for this?

Environment

None

Attachments

1

Activity

Show:

Frédéric Delaporte 
February 6, 2017 at 6:12 PM

Not really an "answer", at best a workaround for your case where it seems you do not need polymorphism queries. There is still actually a bug, but now followed with https://nhibernate.jira.com/browse/NH-3850#icft=NH-3850 since it was almost the same case.

Pieter Willemsen 
February 6, 2017 at 10:04 AM

I found the answer. You can disable the inheritance behavior by doing the following on the mapping class (FluentNhibernate in my case):

Polymorphism.Explicit();

Alex Zaytsev 
February 2, 2017 at 4:16 AM

Frédéric Delaporte 
January 31, 2017 at 6:32 PM
(edited)

Added a test case project demonstrating the issue in more cases (Any without arguments too), and taking into account a special condition: the issue seems to depend on alphabetical order of class names involved.

Pieter Willemsen 
January 27, 2017 at 3:12 PM

Duplicate

Details

Assignee

Reporter

Labels

Components

Affects versions

Priority

Who's Looking?

Open Who's Looking?
Created January 27, 2017 at 3:07 PM
Updated February 6, 2017 at 6:12 PM
Resolved February 2, 2017 at 4:24 AM
Who's Looking?