如何在EFCore Select中编写内联If语句(SQL IIF)? [英] How to write Inline If Statement(SQL IIF) in EFCore Select?
本文介绍了如何在EFCore Select中编写内联If语句(SQL IIF)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下Customer
表:
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).
如何通过EFCore进行如下查询?
How can I query like the following thru EFCore?
SELECT Id, First, IIF(LocationId in(2), Last, '') FROM Customer;
仅在LocationId == 2
时返回Last
.
- 这可以在Linq-to-Entities中作为动态类型完成吗?
- 如果没有,我可以使用
FromSql()
和QueryTypes
? - 我找到了这个如何使用动态选择中的表达式创建内联if语句"以进行空检查.但是我不熟悉
Expression
类型.但是,这暗示了它的可能性.
- Can this be accomplished in Linq-to-Entities as a dynamic type?
- If not, can I use
FromSql()
andQueryTypes
? - 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.
推荐答案
我相信您正在寻找使用.Select()方法和三元运算符的方法.像这样:
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 : "" });
这篇关于如何在EFCore Select中编写内联If语句(SQL IIF)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文