简体   繁体   中英

NHibernate SaveOrUpdate, error: No persister for

I have a NHibernate mapping for a base class A

class A
{
}

class B : A
{
}

public save(A a)
{
 session.SaveOrUpdate(a);
}

Error: No persister for B

As you can see B has been passed with the correct base type A, but i still get the error about the persister for type B

Does NHibernate support inheritance like this... what can i do?

Update: rewritten answer

Apparently, though I fail to find the definitive source on that, is the actual class important. This makes sense, if you consider that NHibernate uses reflection to find the underlying type. Also, when the mapping is loaded, it decorates your types, so basically they become different types altogether (you can see that when you hover over them while debugging).

This principle basically prevents inheritance downcast-mapping, as your derived type is not mapped it is not decorated and hence not known. If you need to use inheritance, you have a few options:

  1. Make a mapping for the derived class
  2. Add a converter for your class to copy from one type in the other (cast is not enough, it won't change the underlying object)
  3. Use ICloneable

All these methods are rather cumbersome. If your design allows it, instead of inheritance, use partial classes or extension methods. The latter is what I find in my own projects, apparently I ran into this before and made it a custom to use extension methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM