Rob*_*ert 2 c# entity-framework nullreferenceexception
我正在测试(集成)我的存储库层,并且我不断收到来自 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));
}
}
Run Code Online (Sandbox Code Playgroud)
方法:
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();
}
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪:
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
Run Code Online (Sandbox Code Playgroud)
是否有明显我遗漏的东西或 EF 中的错误?
我想出了什么问题。我们的数据库结构很糟糕,实际上在 WebUserGroup(它有一个子 WebUser)和 WebUser(它有 WebUserGroups 的集合)之间存在循环引用。因此,当我为用户克隆所有用户组时,它引用了我最初克隆的用户。不知何故,EF 决定向我发送一个 nullReferenceException。当我将组上的 WebUser 属性更改为新的属性时,效果很好。现在是时候和我的 DBA 谈谈更新这个了……
| 归档时间: |
|
| 查看次数: |
1442 次 |
| 最近记录: |