属性可为空时如何编写EF Core投影查询避免空值异常?
解决EF Core投影中Nullable对象的“Nullable object must have a value”异常
问题场景
定义了以下模型:
public class Document { public long Id; public DocumentCategory? Category; } public class DocumentCategory { public long Id; public string Name; }
尝试编写如下查询:
private Expression<Func<Document, Document>> GetProjection() { return x => new Document { Id = x.Id, Category = new DocumentCategory() { Id = x.Category.Id, Name = x.Category.Name, } }; } return await _context.Documents .AsNoTracking() .Select(GetProjection()) .Where(x => x.Id == 1) .ToListAsync();
运行时抛出异常:Nullable object must have a value.
原因
Document.Category是可空引用类型,当数据库中目标Document的Category字段为null时,直接访问x.Category.Id会触发空引用访问。EF Core在解析表达式树时无法处理这种潜在的null引用,因此抛出异常。
正确写法
在投影逻辑中先判断x.Category是否为null,再决定是否创建DocumentCategory实例:
private Expression<Func<Document, Document>> GetProjection() { return x => new Document { Id = x.Id, Category = x.Category != null ? new DocumentCategory { Id = x.Category.Id, Name = x.Category.Name } : null }; }
也可以用模式匹配简化判断:
private Expression<Func<Document, Document>> GetProjection() { return x => new Document { Id = x.Id, Category = x.Category is not null ? new DocumentCategory { Id = x.Category.Id, Name = x.Category.Name } : null }; }
这样当x.Category为null时,投影后的Document.Category也会设为null,避免触发空引用异常。
内容的提问来源于stack exchange,提问作者Álvaro García
相关产品推荐
相关产品推荐

