.net 在EF5中的select子句中选择null
我正在尝试将需要的数据选择为简单的匿名类型,以便为Json请求序列化数据.net 在EF5中的select子句中选择null,.net,linq,entity-framework,.net,Linq,Entity Framework,我正在尝试将需要的数据选择为简单的匿名类型,以便为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
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
});
}
但是当我在VAL上调用枚举器时,我得到以下异常
Unable to create a null constant value of type 'Anonymous type'. Only entity types, enumeration types or primitive types are supported in this context.
如果外键为null,我确实需要Secondary
为null。如何直接从select语句中获得一个为null的匿名对象
我的理想解决方案是能够直接序列化结果数据,而无需处理中间数据集。您可以通过始终返回匿名对象(其中匿名对象可能具有空属性)来解决此问题
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
null,如果p.SecondaryId
为null,你可以添加以下内容
//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;
});
我没有“解决方案”本身。为了解决这个问题,我只需投影整个辅助实体。我对这个解决方案不满意
using (var dbContext = new DataContext())
{
var vals = dbContext.Primaries.Select(p => new
{
Name = p.Name,
Secondary = p.Secondary
});
}
显然,投影整个实体类似于“选择*”——这是一种糟糕的做法。根据您的实际查询,它可能不适用于您。请查看此处。。。问题是null看起来像是dup to meth这个问题与你链接到的另一篇文章无关所以你没有null问题?如果您检查并确定您的问题与此无关。好的。你能选择
p.SecondaryId.HasValue吗?new{Name=p.Secondary.Name}:new{Name=(string)null}
?我不想先枚举到pocos,因为那样我就必须在辅助表中包含所有数据。这一点的关键是只针对我需要的内容点击数据库并返回干净的Json。