views:

878

answers:

4

I have a gridview that is bound to the result from an nhibernate query. If the first item in the list is edited the following exception is thrown:

System.Reflection.TargetException: Object does not match target type

It appears that the problem is caused by the fact that databinding can't deal with the first item in the list being a subtype of the other items in the list.

What is a nice / correct way to solve this problem? Currently I have had to turn off nhibernates proxying.

Edit: I have another couple of solutions:

But none of these feel right though...

A: 

I don't use my domain objects in directly in the views. Instead I use the MVVM pattern and create suitable view models that holds non-proxied objects.

HakonB
+2  A: 

Is the root cause due to a proxy object in the list (from lazy loading) or because the list isn't homogeneous (contains multiple types even if they belong to the same class hierarchy)? The problem with non-homogeneous data sets is a known limitation. See this and this.

I don't think there's a solution other than to not use databinding to populate the grid. That's easy enough if it's read-only.

Jamie Ide
A: 

Maybe too late, but I'd just like to throw this into the ring, here is a solution that I've used for this.

It is also called 'SafeBindingList' like the other suggestion above, but, it does not 'clone' objects to solve the problem. It looks at the objects in the list, then if none proxied, the list is returned unmodified. If one or more objects are proxied, it adds an empty proxy to the non-proxied objects, thus making them all the same type.

So, instead returning a List[T] to bind to, use SafeBindingList[T] to ensure all objects have the same type.

This is updated for the version of Castle used with NH2.0.1: http://code.google.com/p/systembusinessobjects/source/browse/trunk/System.BusinessObjects.Framework/Data/SafeBindingLists.cs

Also, credit goes to the original code and poster: https://forum.hibernate.org/viewtopic.php?t=959464&start=0&postdays=0&postorder=asc&highlight=

Brendan Kowitz
A: 

Another solution is to Join Fetch the relation if you know you are going to be Databinding it. E.g. add .SetFetchMode("People", FetchMode.Join). NHibernate should return only domain objects since none of them should be lazy loaded.

Anonymous