Problem rescuing References from a query in Nhibernate Hasmany

Asked

Viewed 208 times

0

I’m using Nhibernate with Webapi have 2 entities Profile & Personal Personal Login may have N Profile and Profile 1 Person Login. However, when I go to the Personal webservicelogin the Profile reference only works if it is NULL if I add a Profile, whenever it is Personal Login Error. I will describe the code here


Profile.Cs

  public class Perfil
{



    public Perfil()
    {

        PessoaLogin = new Collection<PessoaLogin>();

    } 

    public virtual int IdPerfil { get; set; }
    public virtual string Descricao { get; set; }
    public virtual ICollection<PessoaLogin> PessoaLogin { get; set; }
}

Perfilmap.Cs

  public class PerfilMap : ClassMap<Perfil>
{
    public PerfilMap()
    {
        Id(x => x.IdPerfil);

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

        HasMany(x => x.PessoaLogin)
            .Not.LazyLoad()
            .KeyColumn("Id_Perfil");



        Table("Perfil");
    }

}

Personal login.Cs

 public class PessoaLogin:Pessoa
{

    public virtual string Senha { get; set; }

    public virtual Perfil Perfil { get; set; }

}

Personal loginmap.Cs

   public PessoaLoginMap()
    {

        KeyColumn("IdPessoa");

        Map(x => x.Senha)
            .Not.Nullable()
            .Length(MapLength.TextoMini);

        References(x => x.Perfil)
            .Columns("id_Perfil");

        Table("PessoaLogin");


    }


}

When will I consult the webservice

if Personlog in.Profile for Null appears normally exampleinserir a descrição da imagem aqui

Now if I Add a Profile when ordering People give me the following message. inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

Webapiconfig.Cs

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Personal

public class PessoaLoginController : ApiController
{

    private IPessoaLoginRepository _repository44;

    public PessoaLoginController()
    {
        _repository44 = new PessoaLoginRepository();

    }

    [HttpGet]
    public HttpResponseMessage GetAll()
    {
        //var list = _repository44.GetAll11();
        var lists = _repository44.GetAll();
        return Request.CreateResponse(HttpStatusCode.OK, lists);
    }

    [HttpGet] 
    public HttpResponseMessage GetById(int id)
    {
        var acesso = _repository44.Get(id);

        if (acesso == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
        return Request.CreateResponse(HttpStatusCode.OK, acesso);
    }




    [HttpGet]
    public HttpResponseMessage Login(string nome, string senha)
    {
        var obj = _repository44.ValidarLogin(nome, senha);

        if (obj == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
        return Request.CreateResponse(HttpStatusCode.OK, obj);
    }

    [HttpPost]
    public HttpResponseMessage Incluir([FromBody] PessoaLogin pessoalogin)
    {
        pessoalogin = _repository44.Add(pessoalogin);

        if (pessoalogin != null)
        {
            return Request.CreateResponse(HttpStatusCode.Created, pessoalogin);
        }

        return Request.CreateResponse(HttpStatusCode.NotModified);
    }
}

EDIT

Gave the Error:

inserir a descrição da imagem aqui

  • There is nothing wrong with this behavior. What you would like to appear?

  • Hello Gypsy would like to get the reference ID. ---- [{ "id": "1", "Password":"323232", "Profile": 1, "Idpessoa":1, "Name":"JOEL SANTANA"}] ----

  • You want me to serialize just these fields, right?

  • It only works if it is NULL if in the Bank I set the People Idprofile login as NULL it appears to me correct. otherwise of this JSON bug I cannot restore this Person login.Profile

  • That this Profile Field without giving that error.

  • What are you using to return JSON from the Controller? You can edit your question by placing this part?

  • WebApiConfig.css / var json = config.Formatters.JsonFormatter;&#xA; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;&#xA; config.Formatters.Remove(config.Formatters.XmlFormatter); json.SerializerSettings.Referenceloophandling = Newtonsoft.Json.Referenceloophandling.Ignore;

  • Personlogincontroller.css / [Httpget] public Httpresponsemessage Getall() { //var list = _repository44.Getall11(); var lists = _repository44.Getall(); Return Request.Createresponse(Httpstatuscode.OK, lists); }

  • Repository.css / public Ilist<T> Getall() { Return _Connection.session.Createcriteria(typeof(T)). List<T>(); }

  • I was told that it can be infinite loop when I require this Getall Method, so I followed some tutorials to insert that code block in Webapiconfig.css only that even this zicado the reference

  • Please enter the codes in your question, and not as comments. I will reply.

  • Posted........

Show 7 more comments

1 answer

1

You are Serializing a proxy as per this code in comment. There is nothing wrong with how the serializer solves the problem. The reduction of serialized properties is the focus of the issue:

[HttpGet] 
public HttpResponseMessage GetAll() 
{ 
    var lists = _repository44.GetAll(); 
    return Request.CreateResponse(HttpStatusCode.OK, lists);
}

The solution is to implement a contract resolver that serializes the object using the class definition, not the proxy:

public class NHibernateContractResolver : DefaultContractResolver {
    protected override List<MemberInfo> GetSerializableMembers(Type objectType) {
        if (typeof(INHibernateProxy).IsAssignableFrom(objectType)) {
            return base.GetSerializableMembers(objectType.BaseType);
        } else {
            return base.GetSerializableMembers(objectType);
        }
    }
}

When configuring the serializer, pass the contract solver to it (last line):

var json = config.Formatters.JsonFormatter; 
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; 
config.Formatters.Remove(config.Formatters.XmlFormatter); 
json.SerializerSettings.ReferenceLoopHandling =  Newtonsoft.Json.ReferenceLoopHandling.Ignore;
json.SerializerSettings.ContractResolver = new NHibernateContractResolver();
  • I followed your information now gave error type failed to serialize the Response body for content type

  • Hello Gypsy in your reply I put the result of the application. abs Thanks

  • @Danielmachado You are using the whole site wrong. I suggest you read the help topics before you change answers. Your issue has been cancelled. I’m asking the question.

Browser other questions tagged

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