tags:

views:

134

answers:

1

In some (or many) ways linqtosql makes its hard to recreate a very easy sql. I've tried googling but couldn't find any answer on how to convert to linqtosql the code below with a left outer join that has one condition that should evaluate a column value to true. Thanks in advance to anyone who can help (preferably in c#).

SELECT * FROM
StockType INNER JOIN StoreProduct ON StockType.StockTypeID = StoreProduct.StockTypeID

LEFT OUTER JOIN Yield ON Yield.ToStockTypeID = StockType.StockTypeID AND StockType.IsWholeFormForSpecies = 1

LEFT OUTER JOIN YieldGrade ON YieldGrade.YieldID = Yield.YieldID AND YieldGrade.SizeGradeCode = 'B'

A: 

An example left outer join using multiple conditions, but not your complete query:

var query = from s in db.StockType 
    join y in db.Yield on 
        new { s.StockTypeID, s.IsWholeFormForSpecies } 
        equals 
        new { StockTypeID = y.ToStockTypeID, IsWholeFormForSpecies = 1 } 
        into y1
    from y2 in y1.DefaultIfEmpty()
    select new 
    {
        StockType = s,
        Yield = y2
    };
Ben M
Thanks Ben but im getting this error on your linqtosql above from VS2008: "The type of one of the expression in the join clause is incorrect. Type inference failed in the call to 'Join'". Do you know why?
Leo P Santos
Hi, Leon. The definitions of the anonymous types (new { ... }) must match exactly. Therefore StockType.StockTypeID and Yield.ToStockTypeID must be the same type (I had assumed int), and StockType.IsWholeFormForSpecies would need to be an int to match the constant '1'. I'm guessing the error is because Yield.ToStockTypeID is a nullable int, in which case you should be able to substitute: new { StockTypeID = y.ToStockTypeID.Value, ...
Ben M
IsWholeFormForSpecies = true solved the problem. Thanks a lot Ben for the big help. Wish I know how I can add to your reputation.
Leo P Santos
Glad that helped. I'm not sure how it works if you aren't registered, but are you able to upvote / mark the answer as accepted?
Ben M