How to write Inline If Statement(SQL IIF) in EFCore Select?

c# entity-framework-core linq sql

Question

I have the following Customer table:

Id  First    Last   LocationId
0   John     Doe    2
1   Mary     Smith  4

My use case requires column level permissions(predicated on a value in the Entity's table).

How can I query like the following thru EFCore?

SELECT Id, First, IIF(LocationId in(2), Last, '') FROM Customer;

Whereby Last is returned only when LocationId == 2.

1
0
9/5/2019 9:10:40 PM

Accepted Answer

I believe you're looking to use the .Select() method and ternary operator. So something like this:

context.Customer.Select(c => new { c.Id, c.First, Last = c.LocationId == 2 ? c.Last : "" });
1
9/5/2019 9:52:20 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow