Best way to retrieve data for a Datagridview?

1

What is the best way to retrieve data from a table directly to a DataGridView?

I have a lot of doubts, because a lot of people do not recommend using UnitOfWork, which makes it much easier and makes the code much cleaner.

    var unitOfWork = new UnitOfWork(new DBConecta());
    var _registros = unitOfWork.RepoPaises.Get();
    BindingListView<CNAES> _DataView = new BindingListView<CNAES>(_registros);
    dbGride.DataSource = _DataView;

asked by anonymous 10.03.2016 / 21:04

2 answers

0

The way you did it is not wrong.

As a suggestion, in your entity CNAES you could create a property called userName that returns the first and last name

public usuarioNome
{
    get {
        if (usuario == null) return "";
        return usuario.primeiro_nome + " " + usuario.segundo_nome
    }
}

So you can simplify your code to popular your combo dbGride.DataSource = _context.CNAES.ToList();

A good practice would be to also paginate your data using the Take and Skip methods

dbGride.DataSource = _context.CNAES.Skip(100).Take(50).ToList();
    
13.03.2016 / 17:40
0

Well, the best way to do this select, involving an entity and the user table (to fetch the user who last worked in the registry) I found, was this:

    protected override void Retrieve()
    {
        base.Retrieve();
        _context = new DBConecta(this.strConecta);

        var _query = from r in _context.CNAES
                     from u in _context.Usuarios
                     where u.id == r.usuario_id
                     select new { r.id, r.nome, r.ativo, r.created_at, r.updated_at, r.usuario_id, usuarioNome = r.usuario.login };

        dbGride.DataSource = _query.ToList();
        AfterRetrieve();
    }

Doing so, it does not bring all the fields of the users table and yes only the field that I requested. This is very important since a large table, bringing all the data from another referenced table can have a cost!

SELECT

Extent1 . id , Extent1 . nome , Extent1 . ativo , Extent1 . created_at , Extent1 . updated_at , Extent1 . usuario_id , Extent2 . primeiro_nome FROM cnaes AS Extent1 INNER JOIN Usuarios AS Extent2 ON Extent1 . usuario_id = Extent2 . id - Executing at 03/13/2016 16:54:36 -03: 00 - Completed in 0 ms with result: EFMySqlDataReader

For me this was the best solution.

    
13.03.2016 / 21:00