简体   繁体   中英

LINQ to SQL join with LINQ to DataSet

I have a SQL database that I'm using LINQ to connect to (LINQ To SQL) and a local set of XML data (in a dataset). I need to perform an outer left join on the SQL table "tblDoc" and dataset table "document" on the keys "tblDoc:sourcePath, document:xmlLink". Both keys are unfortunately strings. The code I have below doesn't return any results and I've tried a few variations but my LINQ skills are limited. Does anyone have any suggestions or alternate methods to try?

DataColumn xmlLinkColumn = new DataColumn(
    "xmlLink",System.Type.GetType("System.String"));
xmlDataSet.Tables["document"].Columns.Add(xmlLinkColumn);
foreach (DataRow xmlRow in xmlDataSet.Tables["document"].Rows)
{
    xmlRow["xmlLink"] = (string)xmlRow["exportPath"] + 
        (string) xmlRow["exportFileName"];            
}

var query =
    from t in lawDataContext.tblDocs.ToList()
    join x in xmlDataSet.Tables["Document"].AsEnumerable()
    on t.SourceFile equals (x.Field<string>("xmlLink"))
    select new
    {
        lawID = t.ID,
        xmlID = x == null ? 0 : x.Field<int>("id")
    };       

foreach (var d in query.ToArray())
{
    Debug.WriteLine(d.lawID.ToString() + ", " + d.xmlID.ToString());
}

The join clause produces standard inner join behavior. To get an outer join, you need to use the DefaultIfEmpty() extension method:

var query = from t in lawDataContext.tblDocs.ToList()
            join x in xmlDataSet.Tables["Document"].AsEnumerable()
                on t.SourceFile equals (x.Field<string>("xmlLink"))
                into outer
            from o in outer.DefaultIfEmpty()
            select new
            {
                lawID = t.ID,
                xmlID = o == null ? 0 : o.Field<int>("id")
            }; 

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