Adding a case when the class name for entity used in entity framework is same as class name for a web form code-behind file.
Suppose you have a web form Contact.aspx whose codebehind class is Contact and you have an entity name Contact.
Then following code will throw a NullReferenceException when you call context.SaveChanges()
Contact contact = new Contact { Name = "Abhinav"};
var context = new DataContext();
context.Contacts.Add(contact);
context.SaveChanges(); // NullReferenceException at this line
For the sake of completeness DataContext class
public class DataContext : DbContext
{
public DbSet<Contact> Contacts {get; set;}
}
and Contact entity class. Sometimes entity classes are partial classes so that you can extend them in other files too.
public partial class Contact
{
public string Name {get; set;}
}
The error occurs when both the entity and codebehind class are in same namespace.
To fix this, rename the entity class or the codebehind class for Contact.aspx.
**Reason**
I am still not sure about the reason. But whenever any of the entity class will extend System.Web.UI.Page this error occurs.
For discussion have a look at
[To see links please register here]