我需要將從此LINQ返回的數據存儲到實體查詢(下面)到DataTable中,以便我可以將它用作DataGridView的數據源,我該怎麼做?LINQ to Entities查詢到DataTable
在這種情況下,我使用LINQ to Entities來針對實體框架概念模型進行查詢,因此db
是一個繼承自System.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;
}
我試過這樣做(下面),但它在執行過程中會引發異常[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
}
}
[1]:異常:InvalidCastException
Unable to cast object of type 'WhereEnumerableIterator`1[Projeto_TCC.Models.Vendedor]' to type 'System.Collections.Generic.IEnumerable`1[System.Data.DataRow]'.
在此先感謝
如果我像這樣使用方法CopyToDataTable在'query'中將不可用。請注意,我正在使用實體框架。 – Zignd
我在最後一個源文件上輸入了錯字,並且正如編輯所說,CopyToDataTable方法應該在那裏工作。順便說一句 - 答案有幫助嗎? –
正如你可以在同一個鏈接中看到的,爲了獲得對CopyToDataTable方法的訪問,IEnumerable中的T類型必須是DataRow類型,但是相反,您使用了表示數據庫表Vendedor的類,最終我無法訪問那些包含CopyToDataTable的擴展方法。 –
Zignd