Hi all,
I'd like to find out what do you all think of a feature which I think will be pretty useful in some cases.
As everyone knows, NH can only persist/load classes explicitly mapped to database tables in HBM files. On the one hand, this is quite logical. But on the other it limits further use of mapped classes. For instance, it is impossible to inherit from them
and save the ancestor since its type is not mentioned anywhere in the mapping files. Here's an example:
Code:
// Base is mapped to, say, Base table in Base.hbm.xml
class Base
{
public int A
{ get ...; set ... }
protected virtual Foo()
{
// Some logic.
}
}
// Derived has no mapping file
class Derived : Base
{
protected override Foo()
{
// Some other logic
}
}
static void Main()
{
ISession session = sessionFactory.OpenSession();
Base base = new Base();
base.A = 12;
session.Save(base); // This succeeds
base = session.Load(typeof(Base), 2) as Base; // This succeeds as well
base = new Derived(); // Note "Derived" here
base.A = 13;
session.Save(base); // And this fails
// We won't even get here, but if we did,
// this would have failed too
base = session.Load(typeof(Derived), 3) as Derived;
}
As you can see, the logic behind this is quite OOP-ish :) You inherit from some class to extend its functionality and state (in other words, functions and member variables). However, this is not possible with NHibernate, since it requires every derived class to be mapped somehow.
How I see it done (conceptually) is as follows.
Upon persisting an entity NH should traverse a list of base classes of the entity being persisted, until it finds a type which is mapped to a database table. This type is used to persist an entity.
When loading an entity from the database, NH can freely create an instance of derived class, since it is given its type (typeof(Derived) in the example above). Then again it traveses a list of base classes, and loads derived object as an object of base class. Of course some properties remain uninitialized, but that's not a problem, I think.
This would be quite an addition to NH.
Any comments :) ?