C# 实体框架SaveChanges()NullReferenceException,DisplayNameAttribute

C# 实体框架SaveChanges()NullReferenceException,DisplayNameAttribute,c#,entity-framework,C#,Entity Framework,我被困住了,正在寻找任何想法 我有一个实体在保存更改时失败(所有其他实体都工作)。 我已经去掉了我的代码和属性,不需要额外的东西就可以复制了。 我已检查是否可以保存直接访问SQL Server的更改。 通过删除实体并重新添加,我刷新了EF模型。 这个精简的代码不涉及显示名 环境足迹6.1 以下是失败的测试代码: [TestMethod()] public void SaveEntity_ChangeData_ExpectNoErrors() { CaseE

我被困住了,正在寻找任何想法

我有一个实体在保存更改时失败(所有其他实体都工作)。 我已经去掉了我的代码和属性,不需要额外的东西就可以复制了。 我已检查是否可以保存直接访问SQL Server的更改。 通过删除实体并重新添加,我刷新了EF模型。 这个精简的代码不涉及显示名

环境足迹6.1

以下是失败的测试代码:

    [TestMethod()]
    public void SaveEntity_ChangeData_ExpectNoErrors()
    {
        CaseEntities caseEntities = new CaseEntities();
        // Get an existing Entity (this line works)
        var entity = caseEntities.RecordsDistributionPreferences.Find("0001");
        // Change a field
        entity.ModifiedBy = "duncan";

        // get row version before save
        byte[] rowVersionBefore = entity.RowVersion;

        // Save Changes (this next line throws null reference exeption)
        caseEntities.SaveChanges();

        // get row version after save
        byte[] rowVersionAfter = entity.RowVersion;

        // Check that row version are different
        Assert.AreNotEqual(BitConverter.ToInt64(rowVersionBefore.Reverse().ToArray(), 0), BitConverter.ToInt64(rowVersionAfter.Reverse().ToArray(), 0));
    }
异常和堆栈跟踪:

NullReferenceException {"Object reference not set to an instance of an object."}
at System.ComponentModel.DisplayNameAttribute.GetHashCode()
at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)
at System.Collections.Generic.HashSet`1.InternalGetHashCode(T item)
at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value)
at System.Collections.Generic.HashSet`1.UnionWith(IEnumerable`1 other)
at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection, IEqualityComparer`1 comparer)
at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(Type type)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.<>c__DisplayClass4.<GetAttributes>b__3(PropertyInfo pi)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(PropertyInfo propertyInfo)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildPropertyValidator(PropertyInfo clrProperty)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildValidatorsForProperties(IEnumerable`1 clrProperties, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildTypeValidator[T](Type clrType, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties, Func`3 validatorFactoryFunc)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildEntityValidator(InternalEntityEntry entityEntry)
at System.Data.Entity.Internal.Validation.ValidationProvider.GetEntityValidator(InternalEntityEntry entityEntry)
at System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary`2 items)
at System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items)
at System.Data.Entity.DbContext.GetValidationErrors()
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at SCC.Case.Entities.Test.RecordsDistributionPreferenceTest.SaveEntity_ChangeData_ExpectNoErrors() in c:\Dev\SCC\Case\Dev\src\SCC.Case.Entities.Test\RecordsDistributionPreferenceTest.cs:line 40
NullReferenceException{“对象引用未设置为对象的实例。”}
位于System.ComponentModel.DisplayNameAttribute.GetHashCode()处
位于System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)
位于System.Collections.Generic.HashSet`1.InternalGetHashCode(T项)
位于System.Collections.Generic.HashSet`1.AddifyNotPresent(T值)
at System.Collections.Generic.HashSet`1.UnionWith(IEnumerable`1其他)
位于System.Collections.Generic.HashSet`1..ctor(IEnumerable`1集合,IEqualityComparer`1比较器)
位于System.Collections.Generic.HashSet`1..ctor(IEnumerable`1集合)
位于System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(类型)
在System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.c__DisplayClass4.b__3(PropertyInfo pi)
位于System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey,Func`2 valueFactory)
位于System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(PropertyInfo PropertyInfo)
位于System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildPropertyValidator(PropertyInfo clrProperty)
位于System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildValidatorsForProperties(IEnumerable`1 clrProperties,IEnumerable`1 edmProperties,IEnumerable`1 navigationProperties)
位于System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildTypeValidator[T](类型clrType,IEnumerable`1 edmProperties,IEnumerable`1 navigationProperties,Func`3 validatorFactoryFunc)
位于System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildEntityValidator(InternalEntityEntry EntityEntityEntry)
位于System.Data.Entity.Internal.Validation.ValidationProvider.GetEntityValidator(InternalEntityEntry EntityEntityEntry)
位于System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary`2项)
位于System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry,IDictionary`2项)
位于System.Data.Entity.DbContext.GetValidationErrors()处
位于System.Data.Entity.Internal.InternalContext.SaveChanges()处
在System.Data.Entity.Internal.LazyInternalContext.SaveChanges()中
位于System.Data.Entity.DbContext.SaveChanges()处
在c:\Dev\SCC\Case\Dev\src\SCC.Case.Entities.Test.RecordsDistributionPreferenceTest.SaveEntity\u ChangeData\u ExpectNoErrors()中的c:\Dev\SCC\Case\Dev\src\SCC.Case.Entities.Test\RecordsDistributionPreferenceTest.cs:第40行

我建议您将Try-Catch和watch放在内部消息中,在那里您将看到发生了什么,以及什么变量变为null

try{
        CaseEntities caseEntities = new CaseEntities();
        // Get an existing Entity (this line works)
        var entity = caseEntities.RecordsDistributionPreferences.Find("0001");
        // Change a field
        entity.ModifiedBy = "duncan";

        // get row version before save
        byte[] rowVersionBefore = entity.RowVersion;

        // Save Changes (this next line throws null reference exeption)
        caseEntities.SaveChanges();

        // get row version after save
        byte[] rowVersionAfter = entity.RowVersion;

        // Check that row version are different
        Assert.AreNotEqual(BitConverter.ToInt64(rowVersionBefore.Reverse().ToArray(), 0), BitConverter.ToInt64(rowVersionAfter.Reverse().ToArray(), 0));
    }
catch (NullReferenceException ex){

}
在Catch行中放置一个断点,并观察内部消息找到它

问题在于保存实体具有外键的另一个实体。另一个实体只是缺少DisplayName的本地化资源项


我发现问题在于剥离了有问题的DB表的所有外键,然后刷新了数据模型(从DB)。错误消失了。 所以我添加了每个外键,刷新,测试,直到我得到错误。然后我查看了外键实体的显示名,发现缺少一个。

为什么您的单元测试会访问数据库?我创建这个单元测试只是为了调试这个问题。这是我编写一些快速调试代码以剥离应用程序代码层的最简单的地方。一旦问题得到解决,我将删除这个临时单元测试。