简体   繁体   中英

C# Linq CopyToDataTable based of Linq To Sql table class structure

can't quite swing this copyToDataTable method. I'm using Linq to Sql to get my data from the database, but I'm creating my table structures manually and not using DBML files as I found this to be the easiest way to switch between DataContexts manually.

What I get now is the following error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

What I'm doing is this:

[TABLE(Name = "TableA")]
 class TableA
{
    [Column] public string Name;
    [Column] public string surName;
    [Column] public string concatName;
    [Column] public int ID;
}

 Table<TableA> TableA = definedDataContext.GetTable<TableA>();


IEnumerable<DataRow> que =
                    from res in TableA.AsEnumarable()
                    WHERE someListFromParameters.Contains(res.Name)
                    select res;

Datatable result = que.CopyToDataTable();

The error line shows up under the WHERE keyword, so just after the AsEnumarable() statement.

So, do I have to create a DataRow based off the TableA class?

The error occurs because you are trying to implicitly cast IEnumerable<TableA> to IEnumerable<DataRow> .

What you need to do is create a new DataTable and add rows to it (DataRow can not exist without a DataTable).

Here's an example (untested, but you get the idea):

var name = new DataColumn();
name.DataType = typeof(string);
name.ColumnName = "Name";

var surName = new DataColumn();
surName.DataType = typeof(string);
surName.ColumnName = "surName";

var concatName = new DataColumn();
concatName.DataType = typeof(string);
concatName.ColumnName = "concatName";

var id = new DataColumn();
id.DataType = typeof(int);
id.ColumnName = "ID";

var table = new DataTable("TableA");
table.Columns.Add(name);
table.Columns.Add(surName);
table.Columns.Add(concatName);
table.Columns.Add(id);

foreach(var res in TableA.AsEnumerable())
{
    var row = table.NewRow();
    row["name"] = res.Name;
    row["surName"] = res.surName;
    row["concatName"] = res.concatName;
    row["ID"] = res.ID;
    table.Rows.Add(row);
}

One final note, please have a look at your variable/property names to make them consistent.

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