Steven Deam Steven Deam - 1 month ago 13
C# Question

simple LINQ Query gets NullREferenceException even though SQL server table has data

I have a simple Linq query that is failing suddenly. This worked up until yesterday and I have not been able to determine the problem.

The query is simply getting a complete view from the SQL server

using(JobEntities JE = new JobEntities())
{
var BatchData = (from x in JE.vwBatchObjectActiveBatches select x).ToList();
}


Starting yesterday this line gets a NullReferenceException (Object reference not set to an instance of an object). My suspicion was that a user put in bad data causing the view to fail on the sql server, but I have checked the sql server itself and the view runs fine and populates with data.

This query was running in the middle of a larger function loading data from many places, so I have created a test case where I simply load the main window and run this query directly in the code behind to make sure that nothing else is affecting it, and the query still fails. All other Linq queries that I run in this project work still, only this one fails. The app is not under any production right now, and has been static for several months at least.

When I look at the JE in the watch window I can see the vwBatchObjectActiveBatches and it lists 164 records in the Local section -- this matches the view results on the sql server. Expanding the Results View shows the null error again. DebugInformation

How can I find and fix whatever is causing this query to fail? Why does the results view show an error but the local Line shows the data that I am attempting to get?

Answer

It looks like your database returns NULL where Entity Framework does not expect/allow it. Data returned should be in accordance with the definition of its datamodel objects.

Solution: either 'fix' the data, or fix the query that produces it, or change the definition of your datamodel objects to allow NULL for the conflicting field(s).

Comments