构建警告消息导致我尝试将 #nullable enable 指令添加到我的数据实体类中。
但是,我发现当以下代码运行时,这会导致 SqlNullValueException。
var customerId = 5 // a valid key
var db = GetMyDbContext() // my code to get the DbContext
var cust = db.MyExtCustomers.AsNoTracking().SingleOrDefault(x => x.CustomerID == customerId);
异常消息是
System.Data.SqlTypes.SqlNullValueException:'数据为空。这个方法 或者无法对 Null 值调用属性。'
调用堆栈是
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.SqlDataReader.GetString(int i) Line 2122 C#
[Lightweight Function]
Microsoft.EntityFrameworkCore.Relational.dll!Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable<Entities.MYEXTCustomer>.Enumerator.MoveNext() Unknown
System.Linq.dll!System.Linq.Enumerable.TryGetSingle<Entities.MYEXTCustomer>(System.Collections.Generic.IEnumerable<Entities.MYEXTCustomer> source, out bool found) Line 7391 C#
[Lightweight Function]
Microsoft.EntityFrameworkCore.dll!Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute<Entities.MYEXTCustomer>(System.Linq.Expressions.Expression query) Unknown
Microsoft.EntityFrameworkCore.dll!Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute<Entities.MYEXTCustomer>(System.Linq.Expressions.Expression expression) Unknown
dll!Helpers.DataAccessStd2.MakeReadOnlyProperties(string connectionString, int jobId) Line 439 C#
这是设计错误吗?我应该如何解决重构我的类的问题?
如果
_data[i]
永远不应该为 null,并且您不喜欢该异常,请执行以下操作:
_data[i]?.String ?? throw ExceptionOfYourChoice();
如果
_data[i]
有时可以为 null,并且返回 null 也可以,请执行:
_data[i]?.String; // also change the return type to string?
如果
data[i]
有时可以为 null,但您不想返回 null,请执行以下操作:
_data[i]?.String ?? string.Empty;
无论如何,对于可空值,您需要处理
_data[i]
为空。 null 条件运算符(即 ?
)表示“这可能为 null,如果是,则忽略其后面的内容,只使用 null 代替”。