Always when I try to save an object with a collection of data mapped as HasMany
I have to put a circular reference so that NHibernate can save this object cascade.
For example I have the following mapping of the parent class.
public class ClasseMap : ClassMap<Classe>
{
public ClasseMap()
{
Table("tClasse");
HasMany<Metodo>(t => t.Metodos)
.KeyColumn("IdClasse")
.Inverse()
.Cascade
.SaveUpdate();
}
}
And in the child class
public class MetodoMap : ClassMap<Metodo>
{
public MetodoMap()
{
Table("tMetodo");
References(t => t.Classe)
.Column("IdClasse")
.ForeignKey("FK_Metodo_IdClasse");
}
}
When I save the data from my object Classe
I do the following:
public class RepositorioClasse
{
protected readonly ISession SessaoAtual;
public RepositorioClasse(ISession sessaoAtual)
{
SessaoAtual = sessaoAtual;
}
public SalvaEntidades() {
var classe = new Classe();
var metodo = new Metodo(){
Nome= "ToString",
TipoRetorno="String",
Classe= classe
};
classe.Nome = "String";
classe.Metodos.Add(metodo);
SessaoAtual.SaveUpdate(classe);
}
}
If I only put a collection of Metodos
into Classe
and remove the reference from Classe
to Metodo
NHibernate does not save and returns an exception saying that I should have a reference of Classe
in Metodo
.