Error returning data using Fluent Nhibernate (Many to Many)

Asked

Viewed 210 times

0

I have a relationship of many to many (M:M) using Fluent Nhibernate:

Class/Map - Unit:

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 Onegroup:

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 am designing a Web Service using Web API. I have done the tests with insertion and it is working properly. HOWEVER, when trying to return the list of Unidadegrupo (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.Entidades.Unidadegroup'. Path '[1]. Units[0]. Groups'." , "ExceptionType": "Newtonsoft.Json.JsonSerializationException"

Why this happens and how to solve?

  • Place the code where such an error occurs?

1 answer

1

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

When generating the N:N data, 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 thread code below:

https://stackoverflow.com/questions/19664257/why-in-web-api-returning-an-entity-that-has-a-one-to-many-relationship-causes-an

Browser other questions tagged

You are not signed in. Login or sign up in order to post.