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

只愿长相守 提交于 2019-12-13 03:12:49

问题


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.

  • Can this be accomplished in Linq-to-Entities as a dynamic type?
  • If not, can I use FromSql() and QueryTypes?
  • I found this SO How to create “inline if statement” with expressions in dynamic select for null checking. But I am not familiar with Expression type. This implies its possible however.

回答1:


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


来源:https://stackoverflow.com/questions/57812651/how-to-write-inline-if-statementsql-iif-in-efcore-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!