Daniel Kelley
Daniel Kelley

Reputation: 7737

LINQ to SQL - CASE statement with subquery

I am having trouble trying to represent the below SQL (which returns the results I want) in LINQ:

select 
    case r.CategoryID
    when 2 then
        case r.PrimaryRecord
            when 1 then r.RecordID
            else (select RecordID from Record where RecordGroupID = r.RecordGroupID and PrimaryRecord = 1)
        end
    else
        r.RecordID
    end
    as RecordID
    , r.FooID
from Record r
where 
    r.FooID = 3

Each row in the Record table has a unique RecordID. Multiple RecordID's could be associated with a RecordGroupID for CategoryID 2, but only one of them will have the PrimaryRecord field value of 1.

Given the below table of data, my desired output is RecordID = 1, FooID = 3, i.e. the RecordID for the given RecordGroupID that is the PrimaryRecord, but the FooID for the given row that matches my Where clause.

RecordID    RecordGroupID    PrimaryRecord    CategoryID    FooID  
1           1                1                2             1
2           1                0                2             1
3           1                0                2             3

I appreciate the SQL itself probably isn't the most efficient SQL in the world but it was the best I could come up with.

If anyone could help me create the LINQ statement to represent this query that would be great.

Upvotes: 0

Views: 3152

Answers (1)

aKzenT
aKzenT

Reputation: 7895

I think you don't really need the case in the original query. Try something like:

var matchingRecords = from r in Records
                      where r.FooId = fooId && r.CategoryId == catId && r.RecordGroupId == groupId
                      join r2 in Records on r.RecordGroupId == r2.RecordGroupId && r.CategoryId == r2.CategoryId && r2.PrimaryRecord 
                      select r2;

Edit: added CategoryId in join, assuming RecordGroupId is only unique inside a category.

Upvotes: 2

Related Questions