我正在测试(集成)我的存储库层,并且我不断从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中的错误?
答案 0 :(得分:4)
我弄清楚出了什么问题。我们的数据库结构非常糟糕,WebUserGroup(它有一个子WebUser)和WebUser(它有WebUserGroups集合)实际上有一个循环引用。因此,当我为用户克隆所有UserGroups时,它引用了我最初克隆的用户。不知何故,EF决定向我发送一个nullReferenceException。当我将组上的WebUser属性更改为新组时,它的效果很好。现在是时候和我的DBA谈谈更新这个......