LINQ to Entities query to DataTable

后端 未结 3 1040
天涯浪人
天涯浪人 2021-01-18 17:34

I need to store the data returned from this LINQ to Entities query (below) into a DataTable so that I can use it as data source to a DataGridView, how can I do that?

3条回答
  •  难免孤独
    2021-01-18 18:29

    There is one important thing here, you are casting your Linq query to (IEnumerable) when you are selecting the vendedor, so I assume that vendedor is an instance of Vendedor, so your query will return an IEnumerable

    That should solve your problem, but also, can you try using the generated DataTable as the DataSource for your DataGridView? It would be something like this:

    var query = (from vendedor in db.Vendedores.AsEnumerable()
                       where vendedor.codigo == Convert.ToInt32(textBoxPesquisa.Text)
                       select vendedor);
    var dt = query.CopyToDataTable();
    this.dataGridViewProcura.DataSource = dt;
    

    Hope I can help!

    EDIT

    As a side (and very personal) note, you could try using lambdas on your select, they look prettier :)

    var pesquisa = Convert.ToInt32(textBoxPesquisa.Text);
    var query = db.Vendedores.Where(vendedor => vendedor.codigo == pesquisa);
    
    var dt = query.CopyToDataTable();
    this.dataGridViewProcura.DataSource = dt;
    

    A lot cleaner, don't you think?

    EDIT 2 I've just realized what you said on CopyToDataTable being for DataRow only, so last (admittedly not so clean) solution would be to mimic the logic on the helper?

    public DataTable CopyGenericToDataTable(this IEnumerable items)
    {
        var properties = typeof(T).GetProperties();
        var result = new DataTable();
    
        //Build the columns
        foreach ( var prop in properties ) {
            result.Columns.Add(prop.Name, prop.PropertyType);
        }
    
        //Fill the DataTable
        foreach( var item in items ){
            var row = result.NewRow();
    
            foreach ( var prop in properties ) {
                var itemValue = prop.GetValue(item, new object[] {});
                row[prop.Name] = itemValue;
            }
    
            result.Rows.Add(row);
        }
    
        return result;
    }
    

    Now, things to consider:

    • This solution will not work with complex properties
    • Customizing the resulting table might be a bit tricky

    While this might solve the issue, I don't think this is a very good approach, but it could be the start of a decent idea :)

    I hope I can help this time!

提交回复
热议问题