Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 890
veronika.np Avatar asked Mar 02 '26 22:03

veronika.np


1 Answers

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.

like image 191
Tim Rogers Avatar answered Mar 04 '26 20:03

Tim Rogers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!