【发布时间】:2020-01-08 18:42:08
【问题描述】:
我有以下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 时返回。
- 这可以在 Linq-to-Entities 中作为动态类型完成吗?
- 如果没有,我可以使用
FromSql()和QueryTypes吗? - 我找到了这个 SO How to create “inline if statement” with expressions in dynamic select for null checking。但我不熟悉
Expression类型。然而,这意味着它是可能的。
【问题讨论】:
-
为什么要在 SQL 中这样做?似乎在 SQL(特别是 EF)中实现它的困难可以很容易地被调用者替换。
-
IIF基本上是CASE表达式的语法糖...stackoverflow.com/questions/46560686/… -
为什么不直接使用 C# 三元运算符
?:呢? (from c in Customer select new { c.Id, c.First, Last = (new[] { 2 }.Contains(c.LocationId) ? c.Last : "") })
标签: c# sql linq entity-framework-core