NHibernate with Assigned Table Column Identifier
by David on Okt.22, 2009, under .NET, NHibernate, Software-Development
Hi all,
in my last Blog http://www.richter-web.info/Wordpress/?p=132 I explained why I have to use external method created row Ids. So some outside method calculates the Id of the new table row. I assign then the value to the entity.
To convey this to Nhibernate( Fluent NHibernate) one has to do the following:
public class Appendix
{
public virtual int id { get; set; }
public virtual AppendixHierarchy AppendixHierachy { get; set; }
public virtual byte[] appendix { get; set; }
}
public class AppendixMap : ClassMap<Appendix>
{
public AppendixMap ()
{
Id(x => x.id).GeneratedBy.Assigned();
References(x => x.AppendixHierachy).ColumnName(”appendixHierarchyId”);
Map(x => x.appendix);
}
}
Now Nhibernate does know that the Ids will be set by “hand”.
But this approach has disadvantages:
Nhibernate does not know anymore if some object is transient or not, since after the Id is set by my code it has an value. For Nhibernate this value means that this object is already in the db. This means one cannot use SaveOrUpdate() anymore. If I do nevertheless nothing happens. So I have to take care of the Save and Update calls and have to distinguish between both.
Also I discovered that the newly created entities are not saved after calling Save:
using (ISession sess = DBSessionManager.GetDBSessionController(Database).GetDBSession())
{
sess.Save(item);
}
Even the closing of the session does not write the changes. This issue was only solved by call sess.Flush();
There is the question also represented: http://stackoverflow.com/questions/1566678/nhibernate-fluent-domain-object-with-idx-x-id-generatedby-assigned-not-savea
another possibility would be to wrap the whole thing into an transaction.
Conclusion: My guess is that the change tracking in the case of the usage of self assigned Id will not work properly. It works because Flush does the right thing. Nevertheless closing the session should have the same impact If it looks into the change tracking records. In the next time I will try to use a more recent NH version… result I will post here….