A build warning message caused me to try adding the #nullable enable directive to my data entity class.
However I found this causes an SqlNullValueException when the following code runs.
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);
The exception message is
System.Data.SqlTypes.SqlNullValueException: ‘Data is Null. This method
or property cannot be called on Null values.’
The call stack is
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#
Is this error by design? How should I tackle refactoring my class?
0
So I originally assumed that it was just a data problem, and your data was null… but I think it’s because EF Core is lazily loading the data behind the scenes. See the EF Core docs for more info.
Basically when you do that .String
it actually goes to look up the data for the first time, so the problem isn’t in that call. It’s in the data lookup.
To get it working properly, you need to change the customer lookup and use the null-forgiving operator. Here’s the example EF Core gives:
var order = context.Orders
.Where(o => o.OptionalInfo!.SomeProperty == "foo")
.ToList();
Translating it to your code, I think this might work for you:
var cust = db.MyExtCustomers.AsNoTracking().SingleOrDefault(x => x!.CustomerID == customerId);
Note the extra null-forgiving operator !
after the x
.
I think this can only happen though if you’ve got some relationships here which you’re not showing as part of this code (ie: x!.CustomerId
is really x.Thing!.CustomerId
) and Thing
is sometimes null.
If that’s not the case, the data is actually null and something is up with your call. Try adding a .ToList()
to your customer look-up to force it to load, then you can see more clearly what the results of that query are.