When adding a new object to my DbContext, I am getting a nullreferenceexception
thrown from inside of Entity Framework.
Stack Trace:
at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.GetOtherEndOfRelationship(IEntityWrapper wrappedEntity)
at System.Data.Entity.Core.Objects.EntityEntry.AddRelationshipDetectedByForeignKey(Dictionary`2 relationships, Dictionary`2 principalRelationships, EntityKey relatedKey, EntityEntry relatedEntry, RelatedEnd relatedEndFrom)
at System.Data.Entity.Core.Objects.EntityEntry.DetectChangesInForeignKeys()
at System.Data.Entity.Core.Objects.ObjectStateManager.DetectChangesInForeignKeys(IList`1 entries)
at System.Data.Entity.Core.Objects.ObjectStateManager.DetectChanges()
at System.Data.Entity.Core.Objects.ObjectContext.DetectChanges()
at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force)
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
The actual lines of code that causes it:
var convertedFoos = ReadFoosFromForeignSource(); //returns a list of anonymous objects with two fields: Foo Original, Foo Converted
UpdatedFooData(convertedFoos.Where(x => x.Original != null));
var newFoos = convertedFoos.Where(x => x.Original == null).Select(x => x.Converted).ToList();
foreach (Foo newFoo in newFoos)
{
db.Foos.Add(newFoo); //error happens here
}
I am reading Foo XML from a foreign source and converting it to local Foo format and then either: updating the existing object or adding the new object to the database.
When the error is thrown (shown by a comment above), db, db.Foos, and newFoo are not null. Inspected newFoo more closely reveals tons of null properties inside of newFoo, but they are all allowed to be null.
Based on the stacktrace I am making the assumption that this is related to collection properties. So I inspected the collection properties more closely and found that none of the collections are null and none of the FK properties of the collection objects are null.