3

I have a situation that I am currently unsure of how to proceed.

I have two datatables that are populated from a database, I also have a list of column names available that can be used to join these two datatables together. I wish to write a set of LINQ queries that will:

  1. Show rows from both datatables (inner join, used for updating one from another).
  2. Show rows from one datatable that don't exist in the other (one query, left join used for inserts, the other a right join used for deletes).

Now I know how to do this with normal LINQ to objects or datatables, however in this case I need to apply the columns to join on dynamically, and there could be more than one. Looking at the following partial example code:

table1.AsEnumerable()
.Join(table2.AsEnumerable(),
    dr1 => dr1.Field<string>("ID"),
    dr2 => dr2.Field<string>("ID"),
    (dr1, dr2) => new
    {
        FieldID = dr1.Field<string>("ID"),
        CdGroup = dr2.Field<string>("Name")
    })

The issues are that I don't know the field type so the .Field<string> parts of the statement can't be applied. Also if their are multiple join columns, then I will need to have multiple join statements.

I have read up on dynamic LINQ and it seems quite promising, however I haven't managed to find any information on dynamic LINQ joins like I am trying to do. I know I could probably get the same results using nested loops or the.Select() method on the datatable, but I am trying to apply LINQ to some of the tougher queries that I require.

Do anyone have any pointers or examples of how I could achieve this, or should I just revert to using a non-LINQ approach?

Thanks very much.

XN16
  • 5,679
  • 15
  • 48
  • 72

1 Answers1

0

If you are using Entity Framework, you could download the Microsoft Dynamics CRM, and use the pattern answered to this question Is there way to structure a QueryExpression so that you could dynamically handle a unknown number of conditions

There is a construct called QueryExpression from which you can model dynamic queries. See this MSDN article http://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.query.queryexpression.aspx

Community
  • 1
  • 1
John C
  • 880
  • 10
  • 13