NullReferenceException in DbContext.saveChanges() - c#

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.

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.

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.

Related

How should I write Elmah-filter for System.Collections.Generic.KeyNotFoundException

I have Elmah-logging on a web service and it is cluttered with one specific error that is irrelevant for me. I want to filter that error out so I can focus on finding my critical errors. I have tried several different syntaxes in web.config but nothing works for me. I can't alter the code writing the errors to the elmah-log, so I have to filter them out in web.config.
The error I want to filter out looks like this in the xml-file:
<error errorId="ffc921c0-278a-4191-8c7c-8b9f176bebc7"
host="MyServer"
type="System.Collections.Generic.KeyNotFoundException"
message="The given key was not present in the dictionary."
source="mscorlib"
detail="System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at MyCompany.ExternWeb.Services.Models.AOListModel.GetLinks(ResultTable searchResult)"
time="2017-02-01T13:20:54.9789432Z"
/>
My elmah-node in web.config with one of my filters I have tried looks like this:
<elmah>
<errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="D:\LOGS\ELMAH\App_Data" />
<errorFilter>
<test>
<equal binding="Exception.Message" value="The given key was not present in the dictionary." type="string" />
</test>
</errorFilter>
</elmah>
The filter doesn't work. If I change the "value"-attribute in the filter above to a different string I manage to filter out errors when I try to go to a url that doesn't exist. Those errors look like this:
<error errorId="2d885a7b-22db-4754-9d84-02a41aa7f98d"
application="/LM/W3SVC/5/ROOT"
host="MyServer"
type="System.Web.HttpException"
message="The controller for path '/filter5' was not found or does not implement IController."
source="System.Web.Mvc"
detail="System.Web.HttpException (0x80004005): The controller for path '/filter5' was not found or does not implement IController.
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)"
time="2017-02-01T14:36:09.1374682Z"
statusCode="404">
<serverVariables>
...
</serverVariables>
<cookies>
...
</cookies>
</error>
Those errors are filtered out with the below filter:
<equal binding="Exception.Message" value="The controller for path '/filter5' was not found or does not implement IController." type="string" />
I have also tried to use a regex-filter like:
<regex binding="BaseException.Message" pattern="(.*)" />
That works for messages like "The controller for path '/filter5' was not found or does not implement IController." but not for "The given key was not present in the dictionary." Why can't I filter on the "Message"-attribute, no matter what kind of error? How should write my filter?
I guess my problem have to do with the System.Collections.Generic.KeyNotFoundException-type that I want to filter out. Since it is a collection I have to "dig into" the object in some way to apply my filter on the correct attribute. But how?

Debugging compiled function in ASP .NET

I have a website I believe to be in ASP .NET, which is throwing an exception System.NullReferenceException: Object reference not set to an instance of an object.. Stack trace shows as follows:
[NullReferenceException: Object reference not set to an instance of an object.]
SomeScript.getConnection() +32
SomeScript.buildGridData() +299
SomeScript.Page_Load(Object sender, EventArgs e) +92
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +43
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Control.LoadRecursive() +163
System.Web.UI.Control.LoadRecursive() +163
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2603
Same error is occurring for basically all pages of the site which request data, with just the SomeScript in above stack trace alternating for the loading script.
Environmental changes have only been in changing password for a remote SMTP server the site uses for mailing out, but site was continuing to load fine after that change was made.
My feeling is that these errors with the getConnection() method started occurring after a user tried to use said SMTP mailing function within the website and received an error (I was not able to capture the error user received).
I'm a bit lost with debugging any further from here as the getConnection() method seems to be within compiled DLLs and not accessible by me.
What is the next step in trying to remove the error?
Firstly, it's unlikely that an SMTP password change has caused the issue from your description of it. But if that password change was made in the Web.config file, I'd say it's possible it was made less carefully than it should have been, and in fact a database connection-related section in there has been inadvertently modified and is no longer valid.
If you want to be able to debug into the DLL, you can disable the option to debug "Just My Code" in Visual Studio (something like Tools/Options/Debugging) - you should then be able to step down into these DLLs and see where the issue lies. Hopefully it won't require any code changes, and you can just fix up the configuration file.

Getting connection error with local emulator

In my Azure application when I am trying to connect to local emulator, I am getting an error.
The line of code I am getting the error on is:
CloudStorageAccount CSC = CloudStorageAccount.Parse(
RoleEnvironment.GetConfigurationSettingValue("connection"));
In CS Def
<ConfigurationSettings>
<Setting name="connection" />
</ConfigurationSettings>
In .cscfg
<Role name="WebRole1">
<Instances count="1" />
<ConfigurationSettings>
<Setting name="connection" value="UseDevelopmentStorage=true" />
</ConfigurationSettings>
Stack Trace:
at RdGetApplicationConfigurationSetting(UInt16* , UInt16** )
at RoleEnvironmentGetConfigurationSettingValueW(UInt16* pszName, UInt16* pszDest, UInt32 cchDest, UInt32* pcchRequiredDestSize)
at Microsoft.WindowsAzure.ServiceRuntime.Internal.InteropRoleManager.GetConfigurationSetting(String name, String& ret)
at Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue(String configurationSettingName)
at WebRole1._Default.Page_Load(Object sender, EventArgs e) in c:\users\gowdes\documents\visual studio 2010\Projects\WindowsAzureProject20\WebRole1\Default.aspx.cs:line 19
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
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)
this may seem overly simplistic... but double check that the default application is indeed your Cloud Application project and NOT the ASP.NET/Web project. Without the "Cloud" context, you'll definitely get the SHException or something similar.
#Jim O'Neil already pointed out that you need to run with the Cloud project being your startup project to avoid SEHException. I also talk about SEHException in this SO answer.
Looking at your comment above, you said your code hits the else part of:
if (RoleEnvironment.IsAvailable)
That means the role environment (e.g. Windows Azure) is not available and you won't be able to execute:
CloudStorageAccount CSC = CloudStorageAccount.Parse(
RoleEnvironment.GetConfigurationSettingValue("connection"));
This most likely reason is because the Cloud project is not the startup project. Or, possibly the emulator isn't being launched (which happens if you don't run Visual Studio as Administrator).

NullReferenceException on XML Deserialization in dynamically loaded assembly

I'm writing a plugin for a CMS that loads plugin assemblies dynamically using Assembly.load.
Note: For reasons that are irrelevant to go into, the frontend loads the assembly statically, whilst the admin environment loads it dynamically.
My plugin has its own xml configuration file that loads the first time the plugin class is used. The config file is deserialized into an object object using XmlSerializer.
This deserialization works fine when I load the assembly statically through the frontend, however when the admin tries to load it dynamically I get a NullReferenceException from the reader.
I have tried pre-generating the serialization assembly using Sgen and adding it to the "Bin" directory of the admin environment, but this seems to have no effect.
Stack trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderAccessibilityConfig..cctor() +1156
[TypeInitializationException: The type initializer for 'Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderAccessibilityConfig' threw an exception.]
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderAccessibilityConfig..ctor() +0
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializerContract.get_Reader() +44
System.Xml.Serialization.TempAssembly.InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, String encodingStyle) +69
System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events) +101
[InvalidOperationException: There is an error in XML document (0, 0).]
System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events) +613
System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader) +30
CoA.WebUI.Controls.AccessibilityObjects.AccessibilityConfigBase`1.Deserialize(String xml) +196
CoA.WebUI.Controls.AccessibilityObjects.AccessibilityConfigBase`1.LoadFromFile(String fileName) +256
CoA.WebUI.Controls.Accessibility.Configure(Boolean isAdmin) +725
CoA.WebUI.Controls.Accessibility.GetProperties() +118
CMS.Admin.WebUI.CustomControlCreator.GetCustomControlProperties() +194
CMS.Admin.WebUI.CustomControlCreator.BindPropertyControls() +146
CMS.Admin.WebUI.CustomControlCreator.PageLoad() +164
CMS.Admin.WebUI.CustomControlCreator.Page_Load(Object sender, EventArgs e) +47
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Oddly, the stack trace seems to indicate that the XML document is empty, but I'm passing in a StringReader which I have debugged and confirmed is populated with the correct document - it isn't empty.
I figured it out!!!
If anyone else comes across this problem, here is a way of solving it.
Take your serializable object and put it in its own assembly (i.e. its own project in VS). Now you have two dlls. One with your assembly to be dynamically loaded and the other containing your serializable object.
Take the one with your serializeable object and put it in the bin directory of any application that dynamically loads your plugin assembly.
Now when your dynamically loaded assembly tries to create an object, the assembly for creating that object is already available in memory - having been loaded statically.
I don't know why XmlSerializer doesn't like to work when working with a dynamically loaded assembly, but this workaround seems to work well.
Hope this helps someone some day.

ASP + EF loading assembly problem

I have a big problem. When I'm running asp SOMETIMES the application is craching with the following error message:
Schema specified is not valid. Errors:
The types in the assembly 'Data.EF,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' cannot be loaded
because the assembly contains the
EdmSchemaAttribute, and the closure of
types is being loaded by name.
Loading by both name and attribute is
not allowed.
Stack Trace:
[MetadataException: Schema specified
is not valid. Errors: The types in
the assembly 'Data.EF,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' cannot be loaded
because the assembly contains the
EdmSchemaAttribute, and the closure of
types is being loaded by name.
Loading by both name and attribute is
not allowed.]
System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection
objectItemCollection, Assembly
assembly, Boolean
loadReferencedAssemblies,
EdmItemCollection edmItemCollection,
Action1 logLoadMessage) +480
System.Data.Metadata.Edm.ObjectItemCollection.ExplicitLoadFromAssembly(Assembly
assembly, EdmItemCollection
edmItemCollection, Action1
logLoadMessage) +53
System.Data.Metadata.Edm.MetadataWorkspace.ExplicitLoadFromAssembly(Assembly
assembly, ObjectItemCollection
collection, Action1 logLoadMessage)
+93 System.Data.Metadata.Edm.MetadataWorkspace.LoadFromAssembly(Assembly
assembly, Action1 logLoadMessage)
+130 System.Web.UI.WebControls.EntityDataSourceView.ConstructContext()
+585 System.Web.UI.WebControls.EntityDataSourceView.ExecuteSelect(DataSourceSelectArguments
arguments) +76
System.Web.UI.DataSourceView.Select(DataSourceSelectArguments
arguments,
DataSourceViewSelectCallback callback)
+21 System.Web.UI.WebControls.DataBoundControl.PerformSelect()
+143 Telerik.Web.UI.GridTableView.PerformSelect()
+38 System.Web.UI.WebControls.BaseDataBoundControl.DataBind()
+74 Telerik.Web.UI.GridTableView.DataBind()
+363 Telerik.Web.UI.RadGrid.DataBind() +173
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound()
+66 System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls()
+75 System.Web.UI.Control.EnsureChildControls()
+102 Telerik.Web.UI.GridBaseDataList.get_Controls()
+33 Telerik.Web.UI.RadAjaxControl.PopulatePlainPanels(Control
parent, List`1 list, Control root)
+119 Telerik.Web.UI.RadAjaxControl.OnPagePreRender(Object
sender, EventArgs e) +1802
System.EventHandler.Invoke(Object
sender, EventArgs e) +0
System.Web.UI.Control.OnPreRender(EventArgs
e) +8864486
System.Web.UI.Control.PreRenderRecursiveInternal()
+103 System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +2496
I also added LoadFromAssembly before every context call and still the same problem.
context.MetadataWorkspace.LoadFromAssembly(context.GetType().Assembly);
Enviroment: VS 2010, .NET 4.0, C#, EF
Could please somebody help me, to fix this issue?
Thanks in advance,
Best regards.
I was receiving the same error on pages where there was a mixture of EntityDataSource objects and other data access such as ObjectDataSource and/or imperative code.
I took the advice of the MSDN article referenced in the other answer to your question. I.e. to use context.MetadataWorkspace.LoadFromAssembly(...). I actually didn't know how to get a reference to the context instance used by EntityDataSource, and I figured I should DRY it up anyway, so I created a partial class eg:
public partial class YourTypeNameEntities
{
partial void OnContextCreated()
{
this.MetadataWorkspace.LoadFromAssembly(typeof(Full.Namespace.Of.YourTypeNameEntities).Assembly);
}
It still didn't work, but I noticed fairly quickly that when calling DataBind() on a control bound to an EntityDataSource that my OnContextCreated() implementation was not firing!
That was a different issue to which I found a solution... replace the ConnectionString and DefaultContainerName attributes in the EntityDataSource declaration with ContextTypeName. For example:
<asp:EntityDataSource ID="CountrySource" runat="server"
ContextTypeName="Full.Namespace.Of.YourTypeNameEntities" EntitySetName="Country"
OrderBy="it.Name" Where="it.Active==true">
That made sure my OnContextCreated implementation would fire and POOF, the "Loading by both name and attribute is not allowed" problem went away!
It's an old post but I've ran throught this problem twice this week and it seems to, in my case at least, to be related about the fact that I opened a VPN (for a complete other task with no link to this entity projet) and then, this error happened.
I've tried to close my VPN... then close my projet and re-open, completly close my VS without any success. But, restarting my computer make it works back.
Hope this helps if someone get this in same circonstences.
I was seeing the same error message, using EF 5.0 and WCF Data Services 5.2.0. This was a data service using a DbContext-derived class.
The fix for me was to separate code-first EF code from model-first EF code. By moving the code-first code into a separate assembly, the error message went away and things are working. The only way I was able to figure out to try this, is that the [EdmSchema] attribute exists on the code generated from our EDMX; but it doesn't exist on our model (code-first) code.
Hope that helps someone...
I was getting the same error for days. I using was a mixture of EntityDataSource objects and other data access such as ObjectDataSource in the same page. Replaced the EntityDataSource objects with ObjectDataSource. Problem went away!

Categories

Resources