I am using c# with Fluent NHibernate and auto mapping.
Here is some code (truncated for clarity), then I'll explain the problem.
public class Company
{
public virtual string Description { get; set; }
}
public class Stock
{
public virtual Product Product { get; set; }
public virtual Company Company { get; set; }
}
Mapping
mappings.Conventions.Add<CascadeConvention>()
.Conventions.Add<CustomForeignKeyConvention>()
.Conventions.Add<HasManyConvention>()
.Conventions.Add<VersionConvention>()
CascadeConvention
just sets everything to All.CustomForeignKeyConvention
removes the _id that NHibernate usually
appends to foreign key id columns.HasManyConvention
sets all HasMany
's to inverse.VersionConvention
convertion looks like this:
instance.Column("Version");
instance.Default(1);
The problem is that when I insert a new stock record, Nhibernate also updates the version number on the related Company
.
If I had an IList<Stock>
property on the Company
then that would make sense but I don't.
I've done a lot of reading around:
From these, I've tried a whole bunch of things including adding .Not.OptimisticLock()
all over the place. I even added an IList<Stock>
property on Company
so that I could specifically set it as Inverse
, Not.OptimisticLock
, etc. Nothing I do seems to make any difference.
We eventually sorted this by moving to a Session-per-request paradigm. Not sure why it was going wrong or why this fixed it. I wrote numerous unit tests to try and reproduce the behaviour in a more controlled environment without success.
In any case, it works now. There are good reasons session-per-request is often given as the best practice way to manage NHibernate sessions in a web application.