Search code examples
c#inheritancenhibernatefluent-nhibernatelinq-to-nhibernate

Using .Any() in combination with NHibernate and inheritance


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?

Also added in the NHibernate Bug Tracker: https://nhibernate.jira.com/browse/NH-3939


Solution

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

    Polymorphism.Explicit();