NHibernate is modifying property when returning by Web Api

1

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.

HowcanIbedoingtofixthisproblem?

FollowtheclassesPersonClinicaandthenPerson:

    
asked by anonymous 21.07.2016 / 16:15

1 answer

1

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)
        .Not.LazyLoad();
    
  • 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>();
    });
    Mapper.AssertConfigurationIsValid();
    
    // 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