DbContext.saveChanges()中的NullReferenceException

12

在使用Entity Framework 5.0进行编程初学时,我遇到了一个异常,这是我创建的第一个实体

请注意,在此之后创建的所有表都可以正常工作。另外,请注意,我已经采取了重新生成数据库和/或重新启动Visual Studio IDE的常规步骤。

使用模型优先(Model-First)方法,我创建了一个名为Contacts的简单表,定义如下:

  <EntityType Name="Contacts">
    <Key>
      <PropertyRef Name="ContactID" />
    </Key>
    <Property Name="ContactID" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
    <Property Name="Name" Type="nvarchar(max)" Nullable="false" />
  </EntityType>

我随后尝试运行以下代码(从ASP.NET页面的Page_Load中)
            var contact = new DataContext.Contact { Name = aName };

            context.Contacts.Add(contact);
            context.SaveChanges();

(当aName不为null时)

异常:

System.NullReferenceException was unhandled by user code
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=System.Web
  StackTrace:
       at System.Web.UI.ParseChildrenAttribute.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.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 Contactisch._Default.AddContact(String aName) in c:\Projects\Contactisch\Contactisch\Contactisch\Default.aspx.cs:line 32
       at Contactisch._Default.Page_Load(Object sender, EventArgs e) in c:\Projects\Contactisch\Contactisch\Contactisch\Default.aspx.cs:line 14
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 

有人能解释一下这个异常的原因吗?特别是,那个调用ParseChildrenAttribute.GetHashCode的是什么意思?

我发现有人遇到了相同的问题在这里,但没有给出满意的解释。


aName 难道不是空的吗? - Wiktor Zychla
不行。我已经检查过了。更重要的是,那会导致完全不同的异常。 - Paul-Jan
初始化 ContactID var contact = new DataContext.Contact { Name = aName , ContactID = 0 }; 并查看问题是否仍然存在。 - Peuczynski
仍然使用Web Forms而不是Razor,这真是奇怪的。 - Rosdi Kasim
@Peuczyński 问题仍然存在。 - Paul-Jan
2个回答

7
当你创建一个与你的数据库中表同名的ASP.NET网页时,会发生这种情况,从数据库生成edmx和EF类后,Visual Studio将它们放在项目的默认命名空间中,这可能会与网页.aspx.cs文件生成的部分类发生冲突。
您无需移除或重命名网页的.aspx文件,只需更改页面代码后台(myPage.aspx.cs)中声明的partial public class的名称,并适当调整页面的Inherits属性。
<%@Page Title="MyPage" ... Inherts="namespace.newClassName" >

或者,您可以将网页声明为不同的命名空间。


7
问题已解决。
问题的原因有点傻。我使用VS Web Express中的默认ASP.NET Web Forms Application项目进行测试。该项目包含一个名为Contact.aspx的Web表单,因此它已经在与我的Contact实体相同的命名空间中包含了一个部分类Contact
可以理解的是,这对于Entity Framework来说并不友好,导致了上述相当晦涩的错误。删除aspx页面解决了这个问题。

3
我遇到了同样的问题,花费了两个小时才弄清楚。谢谢你的回答,非常有用。 - Diego Mendes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接