views:

33

answers:

1

I think I need to do exactly this, but instead using LINQ to DataSets because the "Transactions" table is in DB2 and there is no data context.

http://stackoverflow.com/questions/1813285/linq-query-across-three-levels-of-tables-to-generate-sum

I setup two DataRelations on the DataSet:
1. relate Categories (ds.tables[0] in my example) to Products (ds.tables[1])
2. relate Products to Transactions (ds.tables[2])

var query = from x in ds.tables[0].AsEnumerable()
    orderby x.Field<int>("Priority")
    select new {
        Name = x.Field<string>("Text"),
        Amount = //maybe using GetChildRows here???
    };

I don't really know what to do about the amount. Thanks in advance!

+1  A: 

If the rows you need in the Transactions table are loaded in ds, then I think you could do this:

DataRelation relationToProducts;
DataRelation relationToTransactions;    
var query = from x in ds.tables[0].AsEnumerable()
orderby x.Field<int>("Priority")
select new {
    Name = x.Field<string>("Text"),
    Amount = x.GetChildRows(relationToProducts)
            .Sum(product => product.GetChildRows(relationToTransactions)
                    .Sum(tx => tx.Field<decimal>("Amount")))
};
Ross Bradbury
I will be testing this shortly.
David
Works perfect with the DataRelation constraints. However, I think I've found another potential caveat. Adding the constraints throws ArgumentException if my Transactions records do not ALL have corresponding parent values. My Transactions table may have records that do not have corresponding parent values in Products. So, maybe using DataRelation and GetChildRows is not the best idea. Should I ask a new question?
David
Fixed: there is another constructor for DataRelation(string, datacolumn, datacolumn, bool) where the bool (createConstraints) can be set to false.
David
Any idea how I could do this without the DataRelation? I'm not sure of the syntax without GetChildRows("relation")
David