如何在EFCore Select中编写内联If语句(SQL IIF)?

时间:2019-09-05 20:34:33

标签: c# sql linq entity-framework-core

我有以下Customer表:

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

我的用例需要列级权限(基于实体表中的值)。

如何通过EFCore进行如下查询?

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

仅在Last时返回LocationId == 2

1 个答案:

答案 0 :(得分:1)

我相信您正在寻找使用.Select()方法和三元运算符。像这样:

context.Customer.Select(c => new { c.Id, c.First, Last = c.LocationId == 2 ? c.Last : "" });