在LINQ SQL ISNULL等效? [英] Equivalent of SQL ISNULL in LINQ?

查看:168
本文介绍了在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 是一组/对象可能为空,你可以检查 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>
}

或者如果你想默认的是(不是

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



更新;在回应downvote,我已经调查了......事实证明,这是正确的做法!下面是关于罗斯文一个例子:

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 - pretty我们要多东西(它不是 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天全站免登陆