I have situation where a few parts of my entity model is known only at runtime. In order to create queries in a simple way I'd like to add a simple one-to-many
association on items referencing them before creating the SessionFactory
.
I've looked at this post in Ayende's blog and Extend/Modify NHibernate classes at runtime but I'm stuck at an error saying:
Unknown collection role: MySandbox.Parent.Children
What is a collection role and how do I instruct NHibernate to resolve it as if it was added in the hbm.xml?
My test:
using (var tx = this.session.BeginTransaction())
{
parent = new Parent() { Name = "Parent 1" };
this.session.Save(parent);
tx.Commit(); //<- The exception is thrown here
}
My code for adding the association:
// var cfg = <init nhibernate>
PersistentClass cls = cfg.GetClassMapping("MySandbox.Parent");
NHibernate.Mapping.Set value = new NHibernate.Mapping.Set(cls)
{
Role = cls.EntityName + ".Children",
IsGeneric = true,
GenericArguments = new Type[] { typeof(Child) }
};
NHibernate.Mapping.Property property = new NHibernate.Mapping.Property()
{
PropertyAccessorName = "noop",
Value = value,
Name = "Children",
PersistentClass = cls
};
cls.AddProperty(property);
My classes:
public class Parent
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
}
public class Child
{
public virtual int ID { get; set; }
public virtual int ParentID { get; set; }
public virtual string Name { get; set; }
}
The assocition mapping I'm trying to create at runtime:
<set name="Children" access="noop">
<key column="ParentID" />
<one-to-many class="MySandbox.Child, MySandbox"/>
</set>
It works perfect if I just create the association in the hbm.xml-file. I've also tried to compare a association created from xml with one created with the code above with no luck.
(Note: If I don't set the Role
-property another exception of "Value cannot be null. Parameter name: key" is thrown.)