I have two tables in an SQL Database named Computer and Department in which they have a 1-To-Many relationship through a table named DepartamentComputer (PK is ComputerId).
I am trying to list all computers with their respective Department Name on a DataGridView but when it comes to the Department on the DataGridView it actually shows the entity instead of the Name of the Department like this: DataGridView row
These are the methods required to get all computers from a generic repository:
public Task<List<TEntity>> GetAllAsync()
{
return Context.Set<TEntity>().ToListAsync();
}
public async Task<IEnumerable<Computadora>> ListarAsync()
{
return await _unitOfWork.Computadora.GetAllAsync();
}
And these are the methods to populate the DataGridView
private async void ListarComputadoras()
{
var lista = await ListarAsync();
Popular(lista);
}
public void Popular(IEnumerable<Computadora> computadoras)
{
var bs = new BindingSource() {DataSource = computadoras.ToList()};
dgvDatos.DataSource = bs;
}
How can I select the property Name of table Department and show it on the DataGridView instead of showing the Name of the Entity?
Thank you!
Edit: I forgot to mention. I want to avoid the use of anonymous types because I have more logic that depends on the list of computers and with anonymous types that logic would break.
Try this
public void Popular(IEnumerable<Computadora> computadoras)
{
var data = (from c in computadoras
select new {
CodigoInterno = c.CodigoInterno,
Departamento = c.Departamento.Name, // If the department entity has a name property.
// assign the properties to be shown in grid like this
}).ToList();
var bs = new BindingSource() {DataSource = data};
dgvDatos.DataSource = bs;
}
If you don't like to use an anonymous type, create a class with the required properties and use it as follows.
public void Popular(IEnumerable<Computadora> computadoras)
{
var data = (from c in computadoras
select new Computer{
CodigoInterno = c.CodigoInterno,
Departamento = c.Departamento.Name, //If the department entity has a name property.
// assign the properties to be shown in grid like this
}).ToList();
var bs = new BindingSource() {DataSource = data};
dgvDatos.DataSource = bs;
}
public class Computer
{
public string CodigoInterno {get;set;}
public string Departamento {get;set;}
//add properties here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.