简体   繁体   English

实体框架SaveChanges()NullReferenceException,DisplayNameAttribute

[英]Entity Framework SaveChanges() NullReferenceException, DisplayNameAttribute

I'm stuck and looking for any ideas. 我被困住并寻找任何想法。

I have one entity that fails on save changes (all other entities work). 我有一个实体在保存更改时失败(所有其他实体都工作)。 I have stripped away my code and attributes to reproduce with nothing extra. 我删除了我的代码和属性,无需额外的重现。 I have checked that I can save changes accessing SQL Server directly. 我已经检查过我可以直接保存访问SQL Server的更改。 I have refreshed the EF model, by dropping the entity and re-adding it. 我通过删除实体并重新添加它来刷新EF模型。 This stripped down code involves no DisplayNames. 这个精简代码不涉及DisplayNames。

EF 6.1 EF 6.1

Here is the failing test code: 这是失败的测试代码:

    [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));
    }

Exeception and StackTrace: Exeception和StackTrace:

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

Found it! 找到了!

The problem was with a different entity that the saving entity had a foreign key to. 问题出在一个不同的实体,即保存实体有一个外键。 This other entity was simply missing a localized resource item for the DisplayName. 这个其他实体只是缺少DisplayName的本地化资源项。

I found the issue my stripping all the foreign keys for the offending DB table, then refreshing the DataModel (from DB). 我发现问题是剥离了令人讨厌的数据库表的所有外键,然后刷新了DataModel(来自数据库)。 Error was gone. 错误消失了。  So I added each foreign key back, refresh, tested until I got the error. 所以我添加了每个外键,刷新,测试,直到我收到错误。 Then I took a look at the DisplayNames for the foreign key entity and found one missing. 然后我看了外键实体的DisplayNames,发现一个丢失了。

i suggest you to put Try Catch and watch inner message, there you will see what's happen and what variable gets null. 我建议你把Try Catch和内部消息放在一起,在那里你会看到发生了什么,什么变量变为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){

}

put a breakPoint in the Catch line, and watch inner Message 在Catch行中放置一个breakPoint,并观察内部消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM