I am using NHibernate 3.1.0.4000 and AutoMapper 2.0.0.0 in a WCF. I have a parent-child relationship I want to maintain from the "many" end. I have no problems maintaining the objects if I do it from the "one" end but in this case that does not make sense. My issue is no matter how I change my mappings, POCOs, etc. the parent object when I attempt to add a child is null in the child causing the insert to fail. What am I missing to get the parent property in the child to populate?
I have a parent-child relationship defined in the following tables:
Create Table Attribute (AttributeUID uniqueidentifier, LongName varchar(20))
Create Table AnswerOption (AnswerOptionID int, AttributeUID uniqueidentifier)
I want the Attribute (parent) to be the owner so I declare the relationship in that mapping file and not in the AnswerOption (child). Though, I have tried with having the relationship bidirectional as well and that has not changed any behaviors in my tests. My mappings apear as follows. Attribute:
<class name="RCAttribute" table="rcs.tblAttribute">
<cache usage="read-write"/>
<id name="ID">
<column name="AttributeUID" />
<generator class="guid" />
</id>
<property name="LongName" type="string" not-null="true" length="200" column="LongName" />
<bag name="AnswerOptions" lazy="true" inverse="true" cascade="all">
<key column="AttributeUID"/>
<one-to-many class="AnswerOption" />
</bag>
</class>
AnswerOption:
<class name="AnswerOption" table="rcs.tblAnswerOption" lazy="true">
<cache usage="read-write"/>
<id name="ID">
<column name="AnswerOptionID" />
<generator class="native" />
</id>
</class>
Attribute Class:
[Serializable]
public class RCAttribute
{
public virtual Guid ID { get; set; }
public virtual string LongName { get; set; }
public virtual ICollection<AnswerOption> AnswerOptions { get; set; }
public RCAttribute() { ID = new Guid("00000000-0000-0000-0000-000000000000"); }
}
AnswerOption Class:
[Serializable]
public class AnswerOption
{
public virtual int ID { get; set; }
public AnswerOption() { ID = 0; }
}
My test procedure looks like this;
public void CreateAnswerOption()
{
AnswerOption newOpt = new AnswerOption();
Attribute.AnswerOptions.Add(newOpt);
Attribute = rc.RCAttributeSave(Attribute);
}
When it goes to create this the Attribute property of the AnswerOption is null so it cannot insert since the parent cannot be null in the child in this case. What am I missing to get it to populate the parent property on the child and be able to insert?
Mapping the collection as inverse without mapping the many-to-one on the other side makes no sense.
You have three options:
Use a bidirectional mapping with inverse="true" on the collection side and set the many-to-one propery (parent reference) in your code before saving the child (yes, I read that you don't want to do it that way).
Only map the collection side (not inverse). NHibernate will then first insert the child with NULL as parent reference, but will update it with the correct parent ID in the same transaction. So you can't have a not null constraint on the parent ID column in the child table (at least it must be deferrable).
(This option only works with NHibernate 3.2.0 or newer) Same as option 2, but add not-null="true" to the key tag in the collection mapping. Then NHibernate will insert the child with the parent ID already set.
Related
I am trying to use NHibernate with an existing database. The database records unidirectional relationships between users:
Users
UserId PK
Name
Relationships
RelationshipId PK
ParentId FK:Users_UserId
ChildId FK:Users_UserId
I want to represent this using NHibernate. At the moment, I have the following POCO object:
class User {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public ICollection<User> ParentUsers {get; set;}
public ICollection<User> ChildUsers {get; set;}
}
I also have this mapping file:
<class name="User" table="Users">
<id name="Id"></id>
<property name="Name"></property>
</class>
I've looked at guides on the web, but I can't work out what I need to put in the mapping file to wire up my two ICollection properties.
How should I map this data structure? Is my current approach correct, or is it better to create a second POCO class, and just use two many-to-one relationships?
I'm probably missing something, but this should get you started:
<idbag name="ParentUsers" table="Relationships">
<collection-id column="RelationshipId" type="...">
<generator class="..."/>
</collection-id>
<key column="ChildId"/>
<many-to-many column="ParentId" class="User"/>
</idbag>
<idbag name="ChildUsers" table="Relationships">
<collection-id column="RelationshipId" type="...">
<generator class="..."/>
</collection-id>
<key column="ParentId"/>
<many-to-many column="ChildId" class="User"/>
</idbag>
Also, one of the collections should be marked as inverse.
How do I map relationship, where child endpoint is exposed via Id property and not via whole Parent object?
Here is the example:
class Parent {
public Guid Id { get; set; }
public List<Child> Chlidren { get; set; }
}
class Child {
public Guid Id { get; set; }
public Guid ParentId { get; set; }
}
Here are the equivalent mappings I'm using:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Blabla"
namespace="Blabla"
auto-import="false">
<typedef name="ChildrenList" class="Blabla" />
<class name="Parent" table="Parent" lazy="false">
<id name="Id" column="ID" type="Guid">
<generator class="guid" />
</id>
<bag name="Children" table="Child"
cascade="save-update"
collection-type="ChildrenList"
lazy="false">
<key column="ParentID" not-null="true" />
<one-to-many class="Child" />
</bag>
</class>
<class name="Child" table="Child" lazy="false">
<id name="Id" column="ID" type="Guid">
<generator class="guid" />
</id>
<!-- How to map ParentID here? -->
</class>
</hibernate-mapping>
When I create a parent, add some children to Children collection and then save the parent, everything is fine. But if save a parent object first, then create a child, setting its ParentID property to ID of the parent, then I get
NHibernate.PropertyValueException:
not-null property references a null or transient value Child._Parent.ChildrenBackref
All attempts to map many-to-one relationship resulted in different exceptions while creating NHibernate configuration. Mostly about object type mismatch.
I'm sure NHibernate is capable to handle this scenario. There must something fairly basic that I miss.
EDIT:
I think it make sense to the example test, which fails with above exception:
var child = new Child(Create.Saved<Parent>().Id); // this sets the ParentId property
this.Repository.Save(child); // here I get the exception
My thoughts why NHibernate is raising this: Children property of Parent class mapped in a way that says that a child cannot exist without a parent (<key column="ParentID" not-null="true" />). When I try to persist a child, NHibernate tries to resolve this relationship (to find a parent this child relates to) and fails, since being given no child endpoint (which otherwise would be ParentId property) in the mapping, it check for its own Child._Parent.ChildrenBackref endpoint, whatever it is.
This looks like a desired solution: Mapping ParentId property as child endpoint of the relationship. This would force NHibernate to resolve a parent by using value of ParentId property as parent's primary key.
The thing is I don't know if it's possible.
The one-to-many / many-to-one relationships you have in NHibernate always needs to have a dominant side (i.e. the side that manages the "saving").
<bag name="Children" table="Child"
cascade="save-update"
collection-type="ChildrenList"
lazy="false">
<key column="ParentID" not-null="true" />
<one-to-many class="Child" />
</bag>
The above is a one-to-many relationship where the dominant side is the parent. That means, you save the parent ... and that will save the parent first, then, the children (with the ParentId being null), then a subsequent update will be issued to set the child.ParentId.
Note:
The child is inserted first with ParentId=null ... if you have a db or mapping restriction to say ParentId cannot be null, this action will fail.
<bag name="Children" table="Child"
cascade="save-update"
collection-type="ChildrenList"
lazy="false"
inverse=true>
<key column="ParentID" not-null="true" />
<one-to-many class="Child" />
</bag>
Note the inverse=true attribute. This means the child object is dominant in the relationship, meaning the child object is in charge. The parent will be inserted, then the Id will be assiged to the child.ParentId, and then the child will be inserted with the ParentId already set.
In many cases, of course, you want to go either way. The easiest way to do this is to manage the relationship on both ends (unfortunately, you have to do this yourself).
On the Parent, you have a method:
public void AddChild(Child child)
{
Children.Add(child);
child.ParentId = Id;
}
public void RemoveChild(Child child)
{
Children.Remove(child);
child.ParentId = null;
}
On the Child, you have a method:
public void SetParent(Parent parent)
{
ParentId = parent.Id;
parent.Children.Add(this);
}
Using these methods to Add/Remove/Set, both sides are consistent after the action is performed. It, then, wouldn't matter whether you set inverse=true on the bag or not.
see http://www.nhforge.org/doc/nh/en/index.html#collections-example
I have the following entities:
namespace NhLists {
public class Lesson {
public virtual int Id { get; set; }
public virtual string Title { get; set; }
}
public class Module {
public virtual int Id { get; set; }
public virtual IList<Lesson> Lessons { get; set; }
public Module() {
Lessons = new List<Lesson>();
}
}
}
And the following mappings:
<class name="Module" table="Modules">
<id name="Id">
<generator class="identity"/>
</id>
<list name="Lessons" table="ModuleToLesson"
cascade="save-update">
<key column="moduleId"/>
<index column="position"/>
<many-to-many
column="lessonId"
class="NhLists.Lesson, NhLists"/>
</list>
</class>
<class name="Lesson" table="Lessons">
<id name="Id">
<generator class="identity"/>
</id>
<property name="Title">
<column name="Title" length="16" not-null="true" />
</property>
</class>
When I delete a lesson by session.Delete(lesson), is there anyway I can have NHibernate automatically update the association in Module.Lessons to remove the entry from the set? Or am I forced to go through all Modules and look for the lesson and remove that by hand?
Edit: Fixed ICollection and <set> in mappings to IList<> and <list> like I want and tested it.
You have false idea. If you want to delete the Lesson object from Module you do that manually. NHibernate just tracks such your action and when session.Commit() is called then the reference between Module and Lesson is deleted in the database.
Calling session.Delete(lesson) deletes the lesson object from database (if foreign keys are set properly then reference between Module and Lesson is deleted of course but it is not responsibility for NHibernate).
In conclusion, it is not possible to delete the lesson object from the Module.Lessons list automatically by calling session.Delete(lesson). NHibernate does not track such entity references.
Turns out that if we do not need IList semantics and can make do with ICollection the update problem can be solved by adding a reference back from Lesson to Module, such as:
public class Lesson {
...
protected virtual ICollection<Module> InModules { get; set; }
...
}
And to the mapping files add:
<class name="Lesson" table="Lessons">
...
<set name="InModules" table="ModuleToLesson">
<key column="lessonId"/>
<many-to-many column="moduleId" class="NhLists.Module, NhLists"/>
</set>
</class>
Then a Lesson deleted is also removed from the collection in Module automatically. This also works for lists but the list index is not properly updated and causes "holes" in the list.
I'm having one self-referencing class. A child has a reference to its parent and a parent has a list of children. Since the list of children is ordered, I'm trying to map the relation using NHibernate's .
This is my mapping:
<class name="MyClass">
<id name="Id">
<generator class="native"/>
</id>
<list name="Children" cascade="delete" inverse="true">
<key column="ParentId"/>
<index column="ListOrder"/>
<one-to-many class="MyClass"/>
</list>
<many-to-one name="Parent" class="MyClass" column="ParentId"/>
</class>
The problem I'm having is when having a bi-directional mapping child<->parent, the list index (ListOrder) isn't updated in the database when I do my CRUD dance. This means that when I e.g. remove a child, I get holes in the children list after saving to the database and fetching the parent again. If I remove the bidirectionality, by not having a many-to-one from the children to the parent (and no inverse=true), the ListOrder is updated correctly.
Have any of you seen this before? Is there any simple solution?
Yes, it's because of inverse=true, an alternate solution would be to use a set or bag instead of list with order="ListOrder", add the ListOrder column as a property to the MyClass class with an empty setter and a getter that always returns it's index from it's parent's child collection. Like this:
<class name="MyClass">
<id name="Id">
<generator class="native"/>
</id>
<bag name="Children" cascade="delete" inverse="true" order-by="ListOrder">
<key column="ParentId"/>
<one-to-many class="MyClass"/>
</bag>
<property name="ListOrder" column="ListOrder"/>
<many-to-one name="Parent" class="MyClass" column="ParentId"/>
</class>
and the class
public class MyClass
{
public virtual int ID { get; set; }
public virtual IList<MyClass> Children { get; set; }
public virtual MyClass Parent { get; set; }
public virtual int ListOrder
{
get
{
if (Parent == null || !Parent.Children.Contains(this)) return -1;
return Parent.Children.IndexOf(this);
}
set { }
}
}
I have a legacy database that I am mapping using NHibernate. The objects of concern are an Account and a list of Notification objects. The objects look like:
public class Notification
{
public virtual int Id { get; set; }
public virtual DateTime BatchDate { get; set; }
/* other properties */
public virtual Account Account { get; set; }
}
public class Account
{
public virtual int Id { get; set; }
public virtual string AccountNumber { get; set; }
/* other properties */
}
The mapping files look like:
<class name="Account" table="Account" dynamic-update="true">
<id name="Id" column="AccountID">
<generator class="native" />
</id>
<property name="AccountNumber" length="15" not-null="true" />
<!-- other properties -->
</class>
<class name="Notification" table="Notification">
<id name="Id" column="Id">
<generator class="native" />
</id>
<!-- other properties -->
<many-to-one name="Account" class="Account" property-ref="AccountNumber" lazy="proxy">
<column name="AcctNum" />
</many-to-one>
However, when I create a criteria such as
return session.CreateCriteria(typeof(Notification)).List<Notification>();
I am getting a Select N+1 case where each account is loaded even though the Account is never referenced. Why are all of the accounts getting loaded when the many-to-one is mapped as a lazy proxy?
The issue is caused by the property-ref attribute. Lazy loading only works when the many-to-one reference is using the other object's primary key since NHibernate assumes there's a foreign key constraint enforcing the validity of such a value. With a non-primary key (indicated by the property-ref), NHibernate does not make this assumption and thus does not assume the related object must exist. Since it does not want to create a proxy for an object that does not exist (i.e. should be null instead of a proxy), it eagerly fetches the remote object. This same issue exists when not-found="ignore" is specified since this indicates that the foreign key relationship is not enforced and may result in a null reference.
See also:
NHibernate creates proxy via session.Load(), but not via Linq or Criteria API
http://frankmao.com/2007/12/05/lazy-load-conflicts-with-property-ref-in-many-to-one-mapping/