等价于 LINQ 中的 SQL ISNULL? [英] Equivalent of SQL ISNULL in LINQ?

查看:32
本文介绍了等价于 LINQ 中的 SQL ISNULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In SQL you can run a ISNULL(null,'') how would you do this in a linq query?

我加入了这个查询:

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?

but I have a column that has a bit type that is non nullable (xx.online) how can I set this to false if it is null?

推荐答案

既然 aa 是可能为 null 的集合/对象,你能不能检查一下 aa == null?

Since aa is the set/object that might be null, can you check aa == null ?

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

(aa / xx might be interchangeable (a typo in the question); the original question talks about xx but only defines aa)

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

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

or if you want the default to be false (not null):

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

<小时>

更新;为了回应反对票,我进行了更多调查......事实是,这是正确的方法!以下是 Northwind 的示例:


Update; in response to the downvote, I've investigated more... the fact is, this is the right approach! Here's an example on 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,但已经足够接近了):

And here's the TSQL - pretty much what we want (it isn't ISNULL, but it is close enough):

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?

这篇关于等价于 LINQ 中的 SQL ISNULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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