Monday, December 12, 2011

cast an NHibernate proxy to a different-than-default type

Let's say Foo is a more specific version of Bar. Let's say that the table for Bar has two columns...

  1. Id
  2. Name

 
 

...and that the table for Foo has two columns...

  1. Id
  2. SomethingMore

 
 

...and that every Id in Foo has a corresponding Id in the Bar table, (although not necessarily the other way around as Baz might also be a child variation of Bar).

 
 

Would there be a way to cast the NHibernate proxy for a Bar to a Foo if the Bar was a Foo? Yes!

var proxy = myObject.ChildrenOfMyObject.First().Bar;

Foo foo = null;

if (proxy is INHibernateProxy)

{

   var lazyInitializer = ((INHibernateProxy)proxy).HibernateLazyInitializer;

   foo = lazyInitializer.GetImplementation() as Foo;

}

var whatever = foo.SomethingMore;

No comments:

Post a Comment