简体   繁体   中英

User-Defined Join of two DataTables

I have created an application where the user can specify queries to databases, maybe even different databases. They would like to have functionality to join the two query results (stored in DataTables) together on user-specified criteria.

The user specifies the join criteria in an XML settings file like this:

<Join Name="join_example" TableAName="tbl_example1" TableBName="tbl_example2" Expression="a.ID == b.ID" />

So far i have converted the DataTables to List of dynamic so the column names are now properties, but I am getting the following error when trying to create the DynamicExpression using those properties:

{"No property or field 'ID' exists in type 'List`1'"}

Any ideas how i can create the dynamic expression? I am open to other ways to perform the join, but would like for the user to be able to use the syntax specified in the XML. Here is my code that is generating the error.

List<dynamic> TableA = ToDynamicList(DataTableA);
List<dynamic> TableB = ToDynamicList(DataTableB);
ParameterExpression paramA = System.Linq.Expressions.Expression.Parameter(TableA.GetType(), "a");
ParameterExpression paramB = System.Linq.Expressions.Expression.Parameter(TableB.GetType(), "b");
Expression Exp = System.Linq.Dynamic.DynamicExpression.Parse(new ParameterExpression[] { paramA, paramB }, TableA.GetType(), this.Expression, new List<dynamic>[] { TableA, TableB });

You don't need to cast the results from tables, you just need to merge them. Here is a linqpad example:

void Main()
{
    var dt1 = new DataTable();
    dt1.Columns.Add("col1", typeof(string));
    dt1.Columns.Add("col2", typeof(int));


    var dt2 = new DataTable();
    dt2.Columns.Add("col1", typeof(string));
    dt2.Columns.Add("col2", typeof(int));

    var row = dt1.NewRow();
    row["col1"] = "one";
    row["col2"] = 1;
    dt1.Rows.Add(row);

    row = dt1.NewRow();
    row["col1"] = "two";
    row["col2"] = 2;
    dt1.Rows.Add(row);

    row = dt2.NewRow();
    row["col1"] = "three";
    row["col2"] = 3;
    dt2.Rows.Add(row);

    row = dt2.NewRow();
    row["col1"] = "four";
    row["col2"] = 4;
    dt2.Rows.Add(row);


    var dtMerged = dt1.AsEnumerable().CopyToDataTable();    // Note: CopyToDataTable requirs that there are rows.  must trap for empty table
    dtMerged.Merge(dt2.AsEnumerable().CopyToDataTable(), true, MissingSchemaAction.Add);

    dtMerged.Dump();
}

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