Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a NullReferenceException in System.Data.Entity.dll (Entity Framework)?

I have a List<State> of State entity objects, and each State object has collections of other objects, such as Licenses, Taxes, Bonds, etc

There's also a collection for ExpiredObjects, which is a list of any object which is expired and needs to be renewed. For some reason, this property is giving me a NullReferenceException when I try and access it for one specific state (Nevada), but I can't for the life of me figure out what is actually null since I don't see any null values anywhere.

Here's my code that throws the exception. It loops through all the states, and adds all the ExpiredObjects to a view-specific collection which gets displayed. My test code is still included

    private List<ExpiredObject> LoadAllExpiredObjects()
    {
        var list = new List<ExpiredObject>();
        foreach (var state in States)
        {
            // This tells me the state is not null, and neither is state.ExpiredObjects
            Debug.WriteLine(string.Format("{0}|{1}|{2}", 
                state.Name, state == null, state.ExpiredObjects == null));

            try
            {
                var x = state.ExpiredObjects;
                Debug.WriteLine(x == null);

                // Exception occurs on the "for" line on the Nevada state only
                // Contents in for loop do not execute
                foreach (var item in x)
                {
                    Debug.WriteLine(string.Format("{0}", item));
                    list.Add(item);
                }

                // This used to be the only line of code before I started testing
                // It fails on Nevada
                //list.AddRange(state.ExpiredObjects);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
            }
        }
        return list;
    }

The stack trace of the error is this:

A first chance exception of type 'System.NullReferenceException' occurred in System.Data.Entity.dll
Object reference not set to an instance of an object.
   at System.Data.EntityKey.AddHashValue(Int32 hashCode, Object keyValue)
   at System.Data.EntityKey.GetHashCode()
   at System.Collections.Generic.GenericEqualityComparer`1.GetHashCode(T obj)
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at System.Data.Objects.ObjectStateManager.TryGetEntityEntry(EntityKey key, EntityEntry& entry)
   at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
   at lambda_method(Closure , Shaper )
   at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
   at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
   at System.Data.Objects.DataClasses.RelatedEnd.Merge[TEntity](IEnumerable`1 collection, MergeOption mergeOption, Boolean setIsLoaded)
   at System.Data.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)
   at System.Data.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)
   at System.Data.Objects.DataClasses.RelatedEnd.Load()
   at System.Data.Objects.DataClasses.RelatedEnd.DeferredLoad()
   at System.Data.Objects.DataClasses.EntityCollection`1.GetEnumerator()
   at MyNamespace.StatesViewModel.LoadAllExpiredObjects() in C:\Users\me\Desktop\MySolution\StatesViewModel.cs:line 217

I also get the exact same error when I select Nevada and it tries to bind a DataGrid to the ExpiredObjects collection (if I comment out that binding, the code works fine)

Does anyone know what could be causing this error?

like image 926
Rachel Avatar asked May 01 '12 19:05

Rachel


People also ask

Why am I getting a NullReferenceException?

This error is caused when an object is trying to be used by a script but does not refer to an instance of an object. To fix this example we can acquire a reference to an instance of the script using GameObject.

How do I fix NullReferenceException in C#?

Solutions to fix the NullReferenceException To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them. In the above example, if(cities == null) checks whether the cities object is null or not.

How do I stop NullReferenceException?

The Null Reference Exception is not a major error, but one of the common ones and one of the basic and simple way to avoid the Null Reference Exception is to check the variable or property before moving ahead and accessing it. And a very basic way to do this is to check the variable within an if statement.

What does NullReferenceException mean?

A NullReferenceException happens when you try to access a reference variable that isn't referencing any object. If a reference variable isn't referencing an object, then it'll be treated as null .


2 Answers

If it's only for Nevada then it must be a data problem, do a thorough check in the db.

And to summarize, the core problem was:

  • It was db-first.
  • ... was returning a null value for one of the fields that was marked in EF as not null
like image 149
Henk Holterman Avatar answered Oct 23 '22 18:10

Henk Holterman


I got the same problem when accidently loading a Module multiple times in a modular Architecture.

Additional, the Module(s) where using 2 copies of the same DbContext, trying to connect one Entity from one Context to another Entity of the other Context.

This masked the InvalidOperationException (cannot use an Entity in multiple Trackers), which occurs normally without the module stuff.

Took me 3 hours to solve, maybe it helps people with the same problem

like image 37
FrankM Avatar answered Oct 23 '22 18:10

FrankM