EF Core查询SQL Server视图抛出SqlNullValueException,如何定位空值?
排查EF Core查询SQL Server视图时的SqlNullValueException异常
问题描述
使用EF Core查询SQL Server视图时抛出System.Data.SqlTypes.SqlNullValueException,但直接在数据库查看视图结果显示无空值,其他视图的查询工作正常。
查询代码:
List<View_ProductWithCategoryTags> prods = _db.View_ProductWithCategoryTags .OrderBy(p => p.ProductName).ToList();
实体类定义:
[Keyless] public partial class View_ProductWithCategoryTags { public long Id { get; set; } public string Description { get; set; } = ""; public string ImageURL { get; set; } = ""; public decimal Price { get; set; } public decimal ProductCost { get; set; } public int ProductId { get; set; } public string ProductName { get; set; } = ""; public string SKU { get; set; } = ""; public int StockQuantity { get; set; } public string Tags { get; set; } = ""; public string Categories { get; set; } = ""; }
排查步骤
用SQL精准检测空值
不要依赖可视化工具的结果,直接执行SQL过滤视图中的空值:SELECT * FROM View_ProductWithCategoryTags WHERE Id IS NULL OR Description IS NULL OR ImageURL IS NULL OR Price IS NULL OR ProductCost IS NULL OR ProductId IS NULL OR ProductName IS NULL OR SKU IS NULL OR StockQuantity IS NULL OR Tags IS NULL OR Categories IS NULL可视化工具可能将空字符串或默认值显示为非空,但数据库中实际存在NULL。
核对实体与视图列的类型及可空性
- 检查视图中
Id列的类型:如果视图里是int而非long,EF Core映射时可能触发转换异常,甚至被误判为空值。 - 数值类型(
decimal、int)若在视图中允许NULL,但实体类定义为非可空,会直接抛出异常。确认视图列的IS NULL约束。
- 检查视图中
查看EF Core生成的实际SQL
启用EF Core日志查看执行的SQL:protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.LogTo(Console.WriteLine, Microsoft.Extensions.Logging.LogLevel.Information); }复制生成的SQL到SSMS执行,验证是否返回空值或存在隐式转换问题。
验证实体类默认值的有效性
实体类中字符串属性的默认值= ""仅在实例化实体时生效,EF Core查询时不会自动将数据库的NULL替换为默认值。可将可能为NULL的属性改为可空类型(如public string? Description { get; set; } = "";),测试是否仍抛出异常。检查视图的定义逻辑
查看视图的SQL源码,确认是否存在LEFT JOIN、聚合函数或子查询可能产生NULL值,尤其是查询时刚好有数据变更导致的瞬时空值。
内容的提问来源于stack exchange,提问作者BedfordNYGuy
相关产品推荐
相关产品推荐

