LINQ to Entities query to DataTable

c# datagridview datatable entity-framework linq

Question

How do I put the information that this LINQ to Entities query returns into a DataTable so that I can use it as the data source for a DataGridView?

In this instance, LINQ to Entities is being used to query an Entity Framework conceptual model.db a class that descended fromSystem.Data.Entity.DbContext .

using (TccContext db = new TccContext())
{
    var query = from vendedor in db.Vendedores.AsEnumerable()
                where vendedor.codigo == Convert.ToInt32(textBoxPesquisa.Text)
                select vendedor;
    // I'd like to do something like DataTable dt = query;
}

This is what I attempted to accomplish (see below), but it fails to execute [1].

using (TccContext db = new TccContext())
{
    IEnumerable<DataRow> query = (IEnumerable<DataRow>)(from vendedor in db.Vendedores.AsEnumerable()
                                                        where vendedor.codigo == Convert.ToInt32(textBoxPesquisa.Text)
                                                        select vendedor);

    using (DataTable dt = query.CopyToDataTable<DataRow>())
    {
        this.dataGridViewProcura.Rows.Add(
            dt.Rows[0][0],  // Código
            dt.Rows[0][1],  // Nome
            dt.Rows[0][2]); // Venda Mensal
    }
}

Exception [1]:InvalidCastException

Unable to cast object of type 'WhereEnumerableIterator`1[Projeto_TCC.Models.Vendedor]' to type 'System.Collections.Generic.IEnumerable`1[System.Data.DataRow]'.

I appreciate you.

1
5
8/25/2013 11:27:35 PM

Popular Answer

ZZZ_tmp
2
8/27/2013 10:58:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow