Entity Framework: Procedure or View with System.NullReferenceException

I was coding a feature that was using a view, it was working fine in development when I had some pretty strict controls over the datasets utilized, but when it got out in the wild it started acting up with the following exception:

Error: System.NullReferenceException: 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()

After digging around for a bit, it turns out the view I was using when connected to live data was actually returning a null value for one of the fields that was marked in the EF as not null. 

The quick fix was to go into the view and change the returning data to not return a null value, but long term is to go into the code and change the field in the Entity Framework model which was marked as not null to NULLABLE and then putting in some parameter validation to handle the null values if they are returned.

Leave a Reply