【问题标题】:Selecting null in a select select clause in EF5在 EF5 的选择选择子句中选择 null
【发布时间】:2013-07-23 01:46:32
【问题描述】:

我正在尝试将我需要的数据选择为简单的匿名类型来序列化 Json 请求的数据。

using (var dbContext = new DataContext())
{
    var vals = dbContext.Primaries.Select(p => new
    {
       Name = p.Name,
       Secondary = p.SecondaryId.HasValue ? new { Name = p.Secondary.Name } : null
    });
}

但是当我在 vals 上调用枚举器时,我得到以下异常

Unable to create a null constant value of type 'Anonymous type'. Only entity types, enumeration types or primitive types are supported in this context.

如果外键为空,我真的需要 Secondary 为空。如何直接从 select 语句中获取匿名为空。

我的想法解决方案是能够直接序列化结果数据,而无需处理中间数据集。

【问题讨论】:

  • 看看这里...问题在于 null stackoverflow.com/questions/682429/…
  • 在我看来像个骗子
  • 此问题与您链接的其他帖子无关
  • 所以你没有空问题?如果您检查并确定您的问题不相关。很好。
  • 可以选择p.SecondaryId.HasValue ? new { Name = p.Secondary.Name } : new { Name = (string)null }吗?

标签: .net linq entity-framework


【解决方案1】:

您可以通过始终返回匿名对象可能具有空属性的匿名来解决此问题。

using (var dbContext = new DataContext())
{
    var vals = dbContext.Primaries.Select(p => new
    {
       Name = p.Name,
       Secondary = new { Name = p.SecondaryId.HasValue ? p.Secondary.Name : null }
    });
}

如果你真的想让Secondary为空,如果p.SecondaryId为空,你可以添加以下内容。

//ToList allows you to work with LINQ to Objects rather than Linq to Entities.  
//However, you'll generally want to call ToList() last for performance reasons.
var valsCleaned = vals.ToList()
                      .Select(v => { 
                                       if(v.Secondary.Name == null)
                                       {
                                           v.Secondary == null;
                                       }
                                       return v;
                                   });

【讨论】:

  • 我不想先枚举到 pocos,因为我必须将所有数据都包含在辅助表中。这样做的重点是只针对我需要的内容访问数据库并返回漂亮干净的 Json。
【解决方案2】:

我本身没有“解决方案”。为了解决这个问题,我简单地投影了整个辅助实体。我对这个解决方案不满意。

using (var dbContext = new DataContext())
{
    var vals = dbContext.Primaries.Select(p => new
    {
       Name = p.Name,
       Secondary = p.Secondary
    });
}

显然,投影整个实体类似于“SELECT *”——这是一种不好的做法。它可能不适合您,具体取决于您的实际查询。

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多