2017-04-05 91 views
0

我在名为Computer和Department的SQL数据库中有两个表,它们通过名为DepartamentComputer(PK是ComputerId)的表有一对多的关系。如何在Entity Framework中列出连接的实体属性而不是完整的实体?

我想列出对一个DataGridView各自的部门名称的所有计算机,但是当涉及到部门的DataGridView的,它实际上显示了实体,而不是系这样的名称:DataGridView row

这些需要方法来从一个通用存储库中获得的所有计算机:

public Task<List<TEntity>> GetAllAsync() 
    { 
     return Context.Set<TEntity>().ToListAsync(); 
    } 

    public async Task<IEnumerable<Computadora>> ListarAsync() 
    { 
     return await _unitOfWork.Computadora.GetAllAsync(); 
    } 

而这些填充的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; 
    } 

如何选择表格部门的属性名称并将其显示在DataGridView上而不是显示实体的名称?

谢谢!

编辑:我忘了提。我想避免使用匿名类型,因为我有更多的逻辑取决于计算机列表和逻辑会破坏的匿名类型。

回答

0

试试这个

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; 
} 

如果你不喜欢使用匿名类型,创建一个类所需要的属性和按如下方式使用它。

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 
} 
+0

我试了一下,它的工作原理,但它可以做到这一点,避免使用匿名类型?因为我有更多的逻辑依赖于计算机列表以及逻辑会破坏的匿名类型。 –

+0

如果您不喜欢使用匿名类型,请为其创建一个类并使用它。查看更新后的答案 – AnjuRaj

相关问题