【问题标题】:Set an List<T> item as empty if returned row is NULL如果返回的行为 NULL,则将 List<T> 项设置为空
【发布时间】:2013-02-05 00:38:27
【问题描述】:

我需要填充List&lt;string&gt;,但是当我的查询返回空值时,此列表中不会创建空字符串。

var maskObj = (from m in context.sistema_DocType_Index
               join n in context.sistema_Indexes on m.indexId equals n.id
               where m.id == docTypeId
               select new maskModel
               {
                    mask = n.mask
               }).ToList();


return Content(""+maskObj.Count());

如果此查询返回 3 行,并且全部为 NULL,我需要列表中的 3 个空字符串。 有什么办法可以实现吗?

我知道对于 Sql Server,NULL 是没有价值的。即使 NULL == NULL 也返回 false,那我该如何继续呢?

【问题讨论】:

  • 添加'where n.mask is not null'怎么样?

标签: c# sql-server entity-framework


【解决方案1】:

我认为您想要类似以下内容:

mask = n.mask ?? string.Empty

如果n.mask 为空,这将使用null-coalescing operator 来使用string.Empty

实体框架生成的SQL应该是这样的:

COALESCE(MASK, '')

当您说“如果此查询返回 3 行,并且全部为 NULL”时,我的回答假设您在谈论 masknull

【讨论】:

    【解决方案2】:

    在查询中添加另一个 where 子句。

    .Where(maskModel => !string.IsNullOrEmpty(maskModel));
    

    【讨论】:

    • 这不是 OP 想要的:他不想排除空行,​​他想为它们提供空条目。
    • 看来你是对的。我会花一些时间在 stackexchange 上进行阅读理解。
    猜你喜欢
    • 2021-04-29
    • 2018-07-30
    • 2016-02-07
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    相关资源
    最近更新 更多