【问题标题】:How to write Inline If Statement(SQL IIF) in EFCore Select?如何在 EFCore Select 中编写内联 If 语句(SQL IIF)?
【发布时间】: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 时返回。

【问题讨论】:

  • 为什么要在 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


【解决方案1】:

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

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

【讨论】:

  • 太好了!谢谢。我为错过这一点而感到无知。还要感谢@NetMage
猜你喜欢
  • 2012-05-03
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-28
  • 2021-10-13
  • 2013-07-07
  • 1970-01-01
相关资源
最近更新 更多