简体   繁体   中英

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

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 .

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 : "" });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM