How to save a cascaded collection in nhibernate without putting circular reference?


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()

      HasMany<Metodo>(t => t.Metodos)

And in the child class

public class MetodoMap : ClassMap<Metodo>
    public MetodoMap()

      References(t => t.Classe)

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",
                           Classe= classe

        classe.Nome = "String";


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 .

asked by anonymous 12.12.2013 / 20:49

2 answers


Looking at your comment:


[...] Having all this information NHibernate could simply   give an insert in the tclass table and then give an insert in the table   tMetodo inserting in the field IdClasse the id of the class that I just   save

This will not happen in this case because in the HasMany clause you defined the relationship as .Inverse() . In practice, what you are saying is that the daughter entity (in this case, Metodo ) is that it will be responsible for keeping track of the relationship between the two (ie the opposite of what you intend). >

If you're keen on English, I suggest reading this NHibernate documentation handbook.

In short: Try removing% with%. It is possible that works.

13.12.2013 / 12:13

Thinking only of database (without NH), how would you do a SELECT in the Methods table to bring the methods of a given Class without having the Class.Id in that table (FK)? Did you see the problem?

It does not make sense to have a collection of Methods within Class without having the Class ID inside Method. It is through this Id that the NH knows which Methods he has to fetch to fill the collection. If we did not have this Class Id, NH would have to fetch ALL records in the Methods table, which means there is no relationship between the two entities.

12.12.2013 / 21:57