简体   繁体   中英

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 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 SQL Server, but I have checked 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 SQL Server. Expanding the Results View shows the null error again.

调试信息

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM