I am assuming nhibernate can handle circular reference issues as I have not seen this mentioned otherwise in the docs or on google (but perhaps I have the wrong terms).
Suppose I have a class which has as a member a reference to an instance of itself:
e.g. class A { A Other; }
I then create 2 objects and have them cross reference one another A a1 = new A(); A a2 = new A();
a1.Other = a2; a2.Other = a1;
I want to produce a set of mappings for these classes such that if I attempt to save a in a session, it will also save b in such a way that b's reference to a is retained.
At the moment I have produced a simple mapping using the many-to-one association (actually this is generated by fluent nhibernate but it looks ok on manual inspection)
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="">
<class name="hibernate.experiment.CircularRefQn+A, hibernate.experiment, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="`A`" xmlns="urn:nhibernate-mapping-2.2">
<id name="Id" type="Int32" column="Id">
<generator class="identity" />
</id>
<many-to-one cascade="all" name="Other" column="Other_id" />
</class>
</hibernate-mapping>
But when I save, a1 does not save the reference to a2 in the database. How can I make it do this?
example code using fluent nhibernate is here (requires nhibernate, fluent-nhibernate and nunit - if people want a stripped down version let me know).
I also created an a3 object which refers to itself and this does not save as I would like.
using System.IO;
using FluentNHibernate.Cfg;
using FluentNHibernate.Mapping;
using NHibernate.Tool.hbm2ddl;
using NUnit.Framework;
namespace hibernate.experiment
{
[TestFixture]
public class CircularRefQn
{
[Test]
public void Test()
{
var file = this.GetType().Name + ".db";
if (File.Exists(file))
File.Delete(file);
var fcfg = Fluently.Configure()
.Database(FluentNHibernate.Cfg.Db.SQLiteConfiguration.Standard
.UsingFile(file))
.Mappings(m =>
{
m.FluentMappings.Add(typeof(A.Map));
m.FluentMappings.ExportTo(".");
})
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))
;
var sFactory = fcfg.BuildSessionFactory();
using (var s = sFactory.OpenSession())
{
A a1 = new A();
A a2 = new A();
a1.Other = a2;
a2.Other = a1;
Assert.NotNull(a1.Other);
Assert.NotNull(a2.Other);
A a3 = new A();
a3.Other = a3;
s.Save(a1);
s.Update(a1);
s.Save(a3);
}
using (var s = sFactory.OpenSession())
{
foreach (var a in s.CreateCriteria(typeof(A)).List<A>())
Assert.NotNull(a.Other);
}
}
public class A
{
public virtual int Id { get; set; }
public virtual A Other { get; set; }
public class Map : ClassMap<A>
{
public Map()
{
Id(x => x.Id);
References(x => x.Other)
.Cascade.All();
}
}
}
}
}