2017-02-22 128 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