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

9

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 .

    
asked by anonymous 12.12.2013 / 20:49

2 answers

2

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
0

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