简体   繁体   中英

Linq results to dataTable with copyToDataTable

I would like to have my Linq results in a dataset/datatable. The problem I have at the moment is the query variable doens't have the propperty copyToDataTable. I get this error.

The type 'x.v_Checklist' cannot be used as type parameter 'T' in the generic type or method 'System.Data.DataTableExtensions.CopyToDataTable

This is my code

protected void btnExcelCheckListDownload_Click(object sender, EventArgs e)
{
    DataSet dsTest = new DataSet();
    var db = new BillingEntities();
    var query = (from u in db.v_Checklist select u).AsQueryable();
    DataTable dt =  query.CopyToDataTable();
    dsTest.Tables.Add(dt);
    ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", dsTest);
}

How can I solve this problem?

From How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow

The CopyToDataTable method takes the results of a query and copies the data into a DataTable, which can then be used for data binding. The CopyToDataTable methods, however, only operate on an IEnumerable source where the generic parameter T is of type DataRow . Although this is useful, it does not allow tables to be created from a sequence of scalar types, from queries that project anonymous types, or from queries that perform table joins.

It's why you can't use directly the CopyToDataTable without writing some extensions.

The linked topic describes how to implement two custom CopyToDataTable<T> extension methods that accept a generic parameter T of a type other than DataRow .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM