tengo unas List<State>
de State
objetos de entidad, y cada State
objeto tiene colecciones de otros objetos, tales como Licenses
, Taxes
, Bonds
, etc¿Por qué obtengo una NullReferenceException en System.Data.Entity.dll (Entity Framework)?
También hay una colección de ExpiredObjects
, que es una lista de todo objeto que es expiró y debe ser renovado. Por alguna razón, esta propiedad me da un NullReferenceException
cuando intento acceder a ella para un estado específico (Nevada), pero no puedo por la vida de mí averiguar qué es realmente null
ya que no veo ningún valor null
en cualquier sitio.
Aquí está mi código que arroja la excepción. Recorre todos los estados y agrega todos los ExpiredObjects
a una colección específica de vista que se muestra. Mi código de prueba se sigue incluyendo
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;
}
El seguimiento de la pila del error es la siguiente:
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
también consigo el mismo error exacto cuando selecciono Nevada y se intenta enlazar un DataGrid
a la ExpiredObjects
colección (si hago un comentario sobre ese enlace, el código funciona bien)
¿Alguien sabe lo que podría estar causando este error?
Si es sólo para Nevada tiene que ser un problema de datos, hacer un control minucioso en el PP. –
@HenkHolterman Lo siento, no estaba seguro de qué información era relevante. Fue db-primero. Todos los objetos ('State',' License', 'Tax', etc.) tienen su propia tabla de base de datos con claves foráneas que los vinculan. También tienen su propia clave principal, y nada es heredado. Estoy investigando los datos ahora - no estoy seguro de por qué no pensé en hacer eso antes de – Rachel
@HenkHolterman Tienes razón, el problema estaba en los datos. El procedimiento que hice para extraer objetos vencidos devolvía un valor 'nulo' para uno de los campos marcados en EF como no nulo, por lo que cada vez que intentaba obtener ese objeto de la base de datos, arrojaba un error. Gracias, y si publica eso como respuesta, lo aceptaré :) – Rachel