gpt4 book ai didi

c# - LINQ 中 SQL ISNULL 的等价物?

转载 作者:IT王子 更新时间:2023-10-29 03:50:32 30 4
gpt4 key购买 nike

在 SQL 中,您可以运行 ISNULL(null,'') 在 linq 查询中如何执行此操作?

我在这个查询中有一个连接:

var hht = from x in db.HandheldAssets
join a in db.HandheldDevInfos on x.AssetID equals a.DevName into DevInfo
from aa in DevInfo.DefaultIfEmpty()
select new
{
AssetID = x.AssetID,
Status = xx.Online
};

但我有一个列的位类型不可为空 (xx.online) 如果它为空,我如何将其设置为 false?

最佳答案

由于 aa 是可能为 null 的集合/对象,您可以检查 aa == null 吗?

(aa/xx 可能可以互换(问题中的错字);原始问题讨论的是 xx 但仅定义了 aa)

select new {
AssetID = x.AssetID,
Status = aa == null ? (bool?)null : aa.Online; // a Nullable<bool>
}

或者如果您希望默认值为 false(而不是 null):

select new {
AssetID = x.AssetID,
Status = aa == null ? false : aa.Online;
}

更新;作为对否决票的回应,我调查了更多……事实是,这是正确的方法!下面是 Northwind 上的一个例子:

        using(var ctx = new DataClasses1DataContext())
{
ctx.Log = Console.Out;
var qry = from boss in ctx.Employees
join grunt in ctx.Employees
on boss.EmployeeID equals grunt.ReportsTo into tree
from tmp in tree.DefaultIfEmpty()
select new
{
ID = boss.EmployeeID,
Name = tmp == null ? "" : tmp.FirstName
};
foreach(var row in qry)
{
Console.WriteLine("{0}: {1}", row.ID, row.Name);
}
}

这里是 TSQL - 几乎是我们想要的(它不是 ISNULL,但足够接近):

SELECT [t0].[EmployeeID] AS [ID],
(CASE
WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(10),@p0)
ELSE [t2].[FirstName]
END) AS [Name]
FROM [dbo].[Employees] AS [t0]
LEFT OUTER JOIN (
SELECT 1 AS [test], [t1].[FirstName], [t1].[ReportsTo]
FROM [dbo].[Employees] AS [t1]
) AS [t2] ON ([t0].[EmployeeID]) = [t2].[ReportsTo]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

QED?

关于c# - LINQ 中 SQL ISNULL 的等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/413084/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com