Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate proxy causing problems with databinding

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:

  • Clone everything in the list (http://steve-fair-dev.blogspot.com/2007/08/databind-object-does-not-match-target.html) - this doesn't work for me as the object doesn't implement ICloneable
  • change the order of items in the list so that the proxy isn't first (http://community.devexpress.com/forums/t/30797.aspx) - this is so hacky, I don't think I can stoop this low!

But none of these feel right though...

like image 354
thatismatt Avatar asked Jan 02 '26 06:01

thatismatt


2 Answers

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.

like image 92
Jamie Ide Avatar answered Jan 03 '26 19:01

Jamie Ide


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=

like image 35
Brendan Kowitz Avatar answered Jan 03 '26 19:01

Brendan Kowitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!