【问题标题】:How to list joined entity property instead of full entity in Entity Framework?如何在实体框架中列出连接实体属性而不是完整实体?
【发布时间】:2017-04-05 19:33:45
【问题描述】:

我在名为 Computer 和 Department 的 SQL 数据库中有两个表,它们通过名为 DepartamentComputer 的表(PK 是 ComputerId)建立一对多关系。

我试图在 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;
    }

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

谢谢!

编辑:我忘了提。我想避免使用匿名类型,因为我有更多依赖于计算机列表的逻辑以及逻辑会中断的匿名类型。

【问题讨论】:

    标签: c# entity-framework datagridview


    【解决方案1】:

    试试这个

    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
    }
    

    【讨论】:

    • 我试过了,它可以工作,但是否可以避免使用匿名类型?因为我有更多依赖于计算机列表的逻辑以及逻辑会中断的匿名类型。
    • 如果您不喜欢使用匿名类型,请为此创建一个类并使用它。查看更新的答案
    猜你喜欢
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多