Error returning data using Fluent NHibernate (Many to Many)

0

I have a many-to-many relationship (M: M) using Fluent NHibernate:

Class / Map - Drive:

public class Unidade
{
    public virtual int Id { get; set; }

    public virtual string Descricao { get; set; }

    public virtual IList<UnidadeGrupo> Grupos { get; set; }

    public Unidade()
    {
        Grupos = new List<UnidadeGrupo>();
    }
}

public class UnidadeMap : ClassMap<Unidade>
{
    public UnidadeMap()
    {
        Id(x => x.Id).GeneratedBy.Assigned();

        Map(x => x.Descricao)
            .Not.Nullable()
            .Length(MapLength.Texto);

        HasManyToMany(x => x.Grupos)
            .Table("UnidadeToGrupo")
            .ParentKeyColumn("Id_Unidade")
            .ChildKeyColumn("Id_UnidadeGrupo");
    }
}

Class / Map UnitGroup:

public class UnidadeGrupo
{
    public virtual int Id { get; set; }

    public virtual string Descricao { get; set; }

    public virtual IList<Unidade> Unidades { get; set; }

    public UnidadeGrupo()
    {
        Unidades = new List<Unidade>();
    }
}

public UnidadeGrupoMap()
{
    Id(x => x.Id);

    Map(x => x.Descricao)
        .Not.Nullable()
        .Length(MapLength.Texto);

    HasManyToMany(x => x.Unidades)
        .Table("UnidadeToGrupo")
        .ParentKeyColumn("Id_UnidadeGrupo")
        .ChildKeyColumn("Id_Unidade");
}

I'm designing a Web Service using Web API. I did the insert tests and it is working correctly. BUT, when attempting to return the list of GetAll, an exception occurs:

  

"Message": "An error has occurred.",   "ExceptionMessage": "The 'ObjectContent'1' type failed to serialize the response body for content type 'application / json; charset = utf-8'."   "ExceptionType": "System.InvalidOperationException",   "StackTrace": null,   "InnerException": {"Message": "An error has occurred.", "ExceptionMessage": "Self referencing loop detected with type 'RemyWebModel.Entities.UnityGroup' Path '[1] .Units [0] .Groups'. ",   "ExceptionType": "Newtonsoft.Json.JsonSerializationException"

Why does this happen and how do I solve it?

    
asked by anonymous 08.08.2014 / 15:32

1 answer

1

After several searches, I understood why the "problem".

When generating the N: N data, it would create an infinite circular loop, exemplifying:

group1: {     description: "group1",    units: [       groups: [          { description: "group1",            units: [ ... ]          }       ]    ] }

That is, the group lists the units, and this in turn lists their groups, and that this again lists units, generating circular reference.

To solve, I used the code from the thread below:

link

    
14.08.2014 / 14:17