我正在测试(集成)我的存储库层,并且不断从EF收到空引用错误。我担心的是,运行调试器时对象null中没有任何内容。实际上,整个方法中没有什么可以为空。所有属性均已在Automapper中正确设置,并且我对所有内容都使用了真实(而非模拟)值。它们都在那里,并使用代码的真实版本。
测试:
[Test]
public void Clone_ShouldCloneUser()
{
using (var scope = new TransactionScope())
{
//arrange
var request = Builder<CloneUserRequest>.CreateNew()
.With(x => x.KeyToClone = 29)
.With(x => x.User = Builder<User>.CreateNew().With(y => y.Key = 0)
.Build())
.Build();
//act
_sut.Clone(request);
//assert
Assert.DoesNotThrow(() => _sut.Clone(request));
}
}
方法:
public void Clone(CloneUserRequest request)
{
var usersGroupsToBeCloned = _context.WebUserGroups.Where(x => x.UserKey == request.KeyToClone).ToList();
var webUser = _mappingService.Map(request.User, new WebUser());
webUser.WebUserGroups = usersGroupsToBeCloned;
//On this line I receive a NullReferenceException, but nothing is null
_context.WebUsers.Add(webUser);
_context.SaveChanges();
}
堆栈跟踪:
System.NullReferenceException : Object reference not set to an instance of an object.
at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.MarkForeignKeyPropertiesModified()
at System.Data.Entity.Core.Objects.DataClasses.EntityReference.AddToNavigationPropertyIfCompatible(RelatedEnd otherRelatedEnd)
at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach)
at System.Data.Entity.Core.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClassd.<Add>b__c()
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)
at Repositories.UserRepository.Clone(CloneUserRequest request) in UserRepository.cs: line 39
at Repositories.UserRepositoryIntegrationTests.Clone_ShouldCloneUser() in UserRepositoryIntegrationTests.cs: line 50
是否有明显的我缺少的东西或EF中的错误?
最佳答案
我弄清楚出了什么问题。我们的数据库结构很糟糕,实际上WebUserGroup(有一个子WebUser)和WebUser(有WebUserGroups的集合)之间有一个循环引用。因此,当我为用户克隆所有UserGroups时,它具有对我最初正在克隆的用户的引用。 EF决定以某种方式向我发送nullReferenceException。当我将网上论坛上的WebUser属性更改为新属性时,它的效果很好。现在是时候与我的DBA讨论有关更新此问题的时间了...
关于c# - NullReferenceException当什么都不为空时?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25370022/