如何在EFCore Select中编写内联If语句(SQL IIF)? [英] How to write Inline If Statement(SQL IIF) in EFCore Select?

查看:385
本文介绍了如何在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.

  • 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.

推荐答案

我相信您正在寻找使用.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆