2017-02-22 127 views
0

使用实体框架,我试图选择记录及其相关的子记录。孩子的记录可能是空的,所以我只想返回一个空字符串,如果他们是。试图运行下面的代码时,我得到一个包含空子实体的Linq查询

空引用异常

var query = ctx.UserAlerts.Include(x=>x.DocumentType).Where(x => x.UserId == userId).ToList(); 
var alerts = query.Select(u => new AlertConfigVM 
      { 
       UserId = u.UserId, 
       Destination = u.AlertDestination, 
       TypeofAlert = u.TypeofAlert, 
       HourInterval = u.IntervalAsHours, 
       DocumentTypeName= u.DocumentType.Name??string.Empty 
      }).ToList(); 

这里有我的实​​体

public class UserAlert 
{ 
    public int Id { get; set; } 
    public string UserId { get; set; } 
    public User User { get; set; } 
    public int TypeofAlert { get; set; } 
    public string AlertDestination { get; set; } 
    public int? DocumentTypeId { get; set; } 
    public virtual DocumentType DocumentType { get; set; } 
    public int? IntervalAsHours { get; set; } 
} 

public class DocumentType 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Key { get; set; } 
} 

,这里是我的返回类型。

public class AlertConfigVM 
{ 
    public int Id { get; set; } 
    public string UserId { get; set; } 
    public User User { get; set; } 
    public int TypeofAlert { get; set; } 
    public string Destination { get; set; } 
    public int? DocumentTypeId { get; set; } 
    public string DocumentTypeName { get; set; } 
    public int? HourInterval { get; set; } 
} 
+0

在检查documenttype.name是否为空之前,确保documentType不为空。 – Forklift

+0

我该怎么做?你能举一个例子吗? –

+1

可能重复[什么是NullReferenceException,以及如何解决它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it ) –

回答

3

更改此:

DocumentTypeName= u.DocumentType.Name??string.Empty 

这样:

DocumentTypeName= u.DocumentType?.Name??string.Empty 

这将使如果空中,DocumentType默认为的String.Empty。

+0

太棒了,完美的工作。我没有意识到你可以做到这一点。你从哪里拿起那个狡猾的小动作? –

+0

老实说,如果我是诚实的,我“意外地”使用ReSharper发现它。 – tjcertified

+2

请注意,此解决方案**仅适用于** Visual Studio 2015及更高版本,使用Roslyn的MSBuild。 – Cameron

1

由于tjcertified's answer只能在Visual Studio 2015年以后,这个解决方案应该无论工作环境:

var query = ctx.UserAlerts.Include(x=>x.DocumentType).Where(x => x.UserId == userId).ToList(); 
var alerts = query.Select(u => new AlertConfigVM 
      { 
       UserId = u.UserId, 
       Destination = u.AlertDestination, 
       TypeofAlert = u.TypeofAlert, 
       HourInterval = u.IntervalAsHours, 
       DocumentTypeName= u.DocumentType != null 
            ? u.DocumentType.Name != null 
             ? u.DocumentType.Name 
             : string.Empty 
            : string.Empty 
      }).ToList(); 

?:操作是ternary operator并且是一样的常规if-else声明。

+3

你可以缩短它:('u.DocumentType == null?null:u.DocumentType.Name)?? string.Empty' –

+0

@AndersonPimentel很好的接收。没有想到这一点。 – Cameron