当前位置:  开发笔记 > 编程语言 > 正文

LINQ中SQL ISNULL的等价物?

如何解决《LINQ中SQLISNULL的等价物?》经验,为你挑选了2个好方法。

在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)如果它为null,如何将其设置为false?



1> Marc Gravell..:

由于aaset/object可能为null,您可以检查aa == null吗?

(aa/ xx可能是可以互换的(问题中的拼写错误);原始问题xx只讨论但只定义aa)

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

或者如果你想要默认值false(不是null):

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

更新; 为了回应downvote,我调查了更多...事实是,这是正确的方法!这是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?



2> bruno conde..:

您可以使用??运算符来设置默认值,但首先必须在dbml文件中的必填字段中设置Nullable属性()truexx.Online

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 ?? false
        };

推荐阅读
mobiledu2402852413
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有