Linq查询包括null子实体

时间:2017-02-22 16:45:20

标签: c# entity-framework linq lambda

使用实体框架,我试图选择记录及其相关的子记录。子记录可以为null,所以我只想返回一个空字符串。我正在接受

  

null引用异常

尝试运行以下代码时。

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; }
}

2 个答案:

答案 0 :(得分:3)

改变这个:

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

到此:

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

如果为null,这将允许DocumentType默认为string.Empty。

答案 1 :(得分: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语句相同。

相关问题