NHibernate View in queryover returns duplicate records

fluent-nhibernate, nhibernate

Solution

NHibernate supports polymorphic queries. So, when you query that base class it will look for all objects derived from that class.

You can control this behavior with the polymorphism attribute on the class mapping.

Implicit polymorphism means that instances of the class will be returned by a query that names any superclass or implemented interface or the class and that instances of any subclass of the class will be returned by a query that names the class itself. Explicit polymorphism means that class instances will be returned only be queries that explicitly name that class and that queries that name the class will return only instances of subclasses mapped inside this `<class>` declaration as a `<subclass>` or `<joined-subclass>`. For most purposes the default, `polymorphism="implicit"`, is appropriate. Explicit polymorphism is useful when two different classes are mapped to the same table (this allows a "lightweight" class that contains a subset of the table columns).

In your example you could set `polymorphism="explicit"` on all 3 mappings.

Problem

I seem to be having a strange problem with one of my database views that I have mapped with NHibernate. I'm getting duplicate records for one of the views I have mapped. I have the following view objects ``` WorkDetailView / \ / \ / \ / \ PickWorkDetailView PutWorkDetailView ``` Each object represents a different view in the database but both `PickWorkDetailView` and `PutWorkDetailView` inherit from `WorkDetailView` because they share many of the same fields. If I run the following piece of code I get 2 results but if I run the actual database view in SQL Management Studio I get 1 result. ``` List<WorkDetailView> workList = session.QueryOver<WorkDetailView>() .List<WorkDetailView>().ToList(); ``` The interesting part is that when I look at all the items in the `workList` collection above I see one `WorkDetailView` object and one `PickWorkDetailView` object. Also if I look at the queries NHibernate is running it issues select from all 3 views (WorkDetailView, PickWorkDetailView and PutWorkDetailView). This does not sound right at all. I can post xml mappings or my fluent mappings if needed.

Original source