How to display data from multiple tables in DataGridView?

0

I'm trying to display multiple tables in DataGridView , from a database I mapped through the Entity Framework .

Example, person table, address.

I tried to use pessoa.BindingSource , then comes the address list, but I could not call the {logradouro, cidade, bairro, estado}

The structure that the Person table is using to define the items / data in the table is:

public virtual ICollection<enderecos> enderecos { get; set; }
    
asked by anonymous 08.06.2018 / 23:26

1 answer

0

You have to create a new class, to be used as a " ViewModel ", or to use anonymous objects:

Class:

public class PessoaViewModel
{
    public string Nome {get;set;}
    public string Endereco {get;set;}
}

Source:

var result = Pessoas.Select(x => new PessoaViewModel(){ Nome = x.Nome, Endereco = x.enderecos.First().Logradouro + ", " + x.enderecos.First().Cidade }).ToList();

dgv.DataSource = result;

Using anonymous objects:

var result = Pessoas.Select(x => new { Nome = x.Nome, Endereco = x.enderecos.First().Logradouro + ", " + x.enderecos.First().Cidade }).ToList();

dgv.DataSource = result;
  

ps. Simple example, without error handling. It is possible that the person has more than one address, so you have to decide which logic will be used to display.

    
09.06.2018 / 07:26