EF6 - Rush load bringing less aggregated data than bank data

5

I'm having the following problem with my relationships in Entity. When I look for example a Bank Client by Id:

return _databaseContext.Clientes
                               .Include(x => x.Enderecos)
                               .Include(x => x.Documentos)
                               .Include(x => x.Telefones)
                               .SingleOrDefault(x => x.Id == id);

It has 2 Addresses, 2 Documents and 3 Telephones. But the Entity only brings 1 document, 1 address and 2 phones. :

I can not understand why. Even using LazyLoad it does not load, except that it is generating an extremely huge and poorly done query with several Unions and SubSelects. Anyone have any ideas?

I'll only put some props because the class is huge:

public class ClienteEntity : Entity<int>
{
    private IList<EnderecoClienteEntity> _enderecos;

    public ClienteEntity(string nome,
        IList<EnderecoClienteEntity> enderecos)
    {
        Nome = nome;


        _enderecos = new List<EnderecoClienteEntity>();
        enderecos.ToList().ForEach(endereco => AddEndereco(endereco));
    }

    public string Nome { get; private set; }


    public virtual ICollection<EnderecoClienteEntity> Enderecos
    {
        get { return _enderecos; }
        private set { _enderecos = new List<EnderecoClienteEntity>(value); }
    }

    public void AddEndereco(EnderecoClienteEntity endereco)
    {
        if(endereco.CriarEndereco())
            _enderecos.Add(endereco);
    }
}

I have discovered where the error is, it is in the list:

public virtual ICollection<EnderecoClienteEntity> Enderecos { get; set; }
  //  {
  //      get { return _enderecos; }
  //      private set { _enderecos = new List<EnderecoClienteEntity>(value);    }
  //   }

If I leave the list like this, it brings everything in the relationship. But what would be the reason?

    
asked by anonymous 11.05.2017 / 19:12

1 answer

3

All this code is useless:

public ClienteEntity(string nome,
    IList<EnderecoClienteEntity> enderecos)
{
    Nome = nome;

    _enderecos = new List<EnderecoClienteEntity>();
    enderecos.ToList().ForEach(endereco => AddEndereco(endereco));
}

public virtual ICollection<EnderecoClienteEntity> Enderecos
{
    get { return _enderecos; }
    private set { _enderecos = new List<EnderecoClienteEntity>(value); }
}

public void AddEndereco(EnderecoClienteEntity endereco)
{
    if(endereco.CriarEndereco())
        _enderecos.Add(endereco);
}

Simplify this to:

public virtual ICollection<EnderecoClienteEntity> Enderecos { get; set; }

It is not you who have to manipulate aggregate entities and levels of protection. It's the Entity Framework that does this. Just let the framework work for you and do not worry so much about code security.

    
11.05.2017 / 20:14