NullReferenceException in DbContext.saveChanges()

2019-01-12 06:09发布

问题:

Taking my very first babysteps with Entity Framework 5.0, I run into an exception with the very first Entity I create.

Please note that every table created after that works just fine. Also, do note that I've taken the usual steps of regenerating the database and/or restarting the Visual Studio IDE.

Using Model-First, I created a trivial table called Contacts, defined as

  <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>

I then tried to run the following code (from the Page_Load of an ASP.NET page)

            var contact = new DataContext.Contact { Name = aName };

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

(with aName != null)

Exception:

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: 

Can someone explain the cause of this exception ? Especially, what is that call to ParseChildrenAttribute.GetHashCode doing there?

I did find someone running into the same issue here, but no satisfactory explanation was given.

回答1:

This happens when you create an ASP.NET webpage with the same name as a table in your database, after generating your edmx and EF classes from your database Visual Studio will place them in the default namespace for your project which causes a conflict with the generated partial class of the web pages .aspx.cs file

You do not need to remove or rename the the .aspx file of your webpage just change the name of the partial public class declared in the pages code behind (myPage.aspx.cs) and adjust the Inherits property of the page appropriately like so.

<%@Page Title="MyPage" ... Inherts="namespace.newClassName" >

Alternatively you could always declare your webpages under a different namespace.



回答2:

Problem solved.

The cause was a bit silly. I was using the default ASP.NET Web Forms Application project from VS Web Express to perform my testing. This project contains a web form called Contact.aspx, so it already includes a partial class Contact in the same namespace as my Contact entity.

Understandably, this didn't play well with Entity Framework, leading to the rather obscure error above. Deleting the aspx page solved the problem.