NHibernate is modifying property when returning by Web Api


I have a web service api where a query is made to the database through nhibernate, but when returning the object, its referenced properties are overwritten, I believe it's because of the nhibernate proxy.



asked by anonymous 21.07.2016 / 16:15

1 answer


As you well suspected the culprit is the NHibernate Proxy. I do not think it's a good idea to serialize the proxy object just because you have little control over it.

Some options:

  • Inform NHibernate not to use proxy in mapping property Pessoa :

    this.References(x => x.Pessoa)
  • Use a cloned object from the original, so you can use the AutoMapper library

    // inicialização do AutoMapper
    Mapper.Initialize(cfg =>
        cfg.CreateMap<PessoaClinica, PessoaClinica>();
        cfg.CreateMap<Pessoa, Pessoa>();
    // usando no controller
    Mapper mapper = new Mapper();
    PessoaClinica obj = ...; // obter o objeto do banco de dados
    return mapper.Map<PessoaClinica, PessoaClinica>(obj);

    Note: You'll probably want to inject dependency on the variable mapper

  • Use a specialized object (DTO) and copy the properties one by one, being that you would return the DTO instead of the proxy within the WebAPI method. You can also use AutoMapper in this option.

  • Customize the serialization process ... this would use a cannon to kill fly

21.07.2016 / 19:55