veronika.np
veronika.np

Reputation: 361

How can I implement select case in Entity Framework?

I have a query with CASE in SQL, how can I do it with Entity Framework?

 DECLARE @SystemTypeId int
 SELECT @SystemTypeId = [SystemTypeId] FROM [Properties] WHERE [Id] = @PropertyId

 SET @RETURN_VAL =
 CASE @SystemTypeId
  WHEN 2 THEN (SELECT [Created] FROM [Assets] WHERE [Id] = @AssetId) 
  WHEN 3 THEN (SELECT dbo.GetAssetValueById([CreatedBy])
               FROM [Assets]
               WHERE [Id] = @AssetId)
  WHEN 9 THEN (SELECT [LastModified]
               FROM [Assets]
               WHERE [Id] = @AssetId)
  ELSE NULL
END

Upvotes: 3

Views: 2901

Answers (1)

Tim Rogers
Tim Rogers

Reputation: 21713

Linq-to-Entities won't generate a CASE statement for you, other than a binary CASE statement when you use the ? : operator.

You can either run it in two queries: get the SystemTypeId first, then run the appropriate query.

Or you can bypass Linq and run the raw SQL, which is often the best approach if you have a complex query.

Upvotes: 3

Related Questions