Getting name associated with province(AdventureWorks2014) exception - c#

im doing test using the AdventureWorks2014 microsoft database with visual studio(coding in C#).I am trying to input StateProvinceID and then display the names(Person.FirstName) that are associated with this StateProvinceID.So far I did this:
static public void provincequery()
{
Console.WriteLine("Enter province ID");
var theid = Convert.ToInt32(Console.ReadLine());
using (var context = new Model1())
{
var queryprovince = from test in context.StateProvince
where test.StateProvinceID == theid
select test;
foreach(var disp in queryprovince)
{
Console.WriteLine("\nProvince:");
Console.WriteLine(disp.Name);
foreach(var test2 in disp.SalesTerritory.Customer)
{
Console.WriteLine(test2.Person.FirstName);
}
}
}
}
however this keeps returning me an error "An error occurred while executing the command definition. See the inner exception for details."
inner exception:
à System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
à System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
à System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
à System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
à System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
à System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
à System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
à System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)
à System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption)
à System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()
à System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)
à System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item)
à System.Data.Entity.DynamicProxies.StateProvince_0A13F786927514ECF26BEB6F7007442E73C1FCAA3A743679986FA051D479F5AA.get_SalesTerritory()
à ConsoleApplication1.Program.requete2() dans c:\Users\julianp\Desktop\ConsoleApplication1\ConsoleApplication1\Program.cs:ligne 152
à ConsoleApplication1.Program.Main(String[] args) dans c:\Users\julianp\Desktop\ConsoleApplication1\ConsoleApplication1\Program.cs:ligne 33
à System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
à System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ThreadHelper.ThreadStart()
I dont really understand why its not working.AdventureWorks schema can be found here:
https://moidulhassan.files.wordpress.com/2014/07/adventureworks2008_schema.gif
thank you

Solved; needed to add ToList() at the end of foreach(var disp in queryprovince).
So its foreach(var disp in queryprovince.ToList())

Related

Graph API - Authentication Token and Task Cancellation Error

We have an application "App1" in Azure will all the required permissions and have 7 instances of a Windows service in C# that uses the same Azure Application "App1" to connect to Outlook Mailboxes. The code is same across all the 7 windows service instances with the difference in config i.e. each instance connecting to a unique Mailbox.
Question:
We do authentication using the code below and each service is running on its own Server(Windows), when this authentication code is executed for lets say all the services will there be issue with the token overlapping since it uses the same Azure "App1" or since its connecting to a unique Mailbox for each service instance it wont be a problem and have unique access token per service instance.
AuthenticationResult authResult = null;
GraphServiceClient graphClient = null;
IMailFolderMessagesCollectionPage inboxMessage = null;
try
{
string tenantId = "TenantId";
string clientId = "ClientId";
string clientSecret = "ClientSecret";
var authority = $"https://login.microsoftonline.com/{tenantId}";
var app = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri(authority))
.Build();
var scopes = new[] { "https://graph.microsoft.com/.default" };
authResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();
}
catch (Exception ex)
{
//return;
}
if (authResult != null)
{
graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(requestMessage =>
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("bearer", authResult.AccessToken);
return Task.FromResult(0);
}));
We get below error frequently and want to know if this setup could be affecting our applications. If not what is the reason we are getting such errors.
Message: System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.HttpProvider.<SendRequestAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.HttpProvider.<SendAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__40.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.BaseRequest.<SendAsync>d__34`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.MessageAttachmentsCollectionRequest.<GetAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at GraphPOC.EmailMain.<GetDataAsync>d__63.MoveNext()
Category: Error
Priority: -1
EventId: 0
Severity: Error
Title:
App Domain: GraphPOC.exe
ProcessId: 988
Process Name: D:\Program Files\GraphPOC.exe
Thread Name:
Win32 ThreadId:4884
Extended Properties:
Callstack= at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at System.Diagnostics.TraceEventCache.get_Callstack()
at System.Diagnostics.TraceListener.WriteFooter(TraceEventCache eventCache)
at Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedTextWriterTraceListener.TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, Int32 id, Object data)
at Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener.TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, Int32 id, Object data)
at Microsoft.Practices.EnterpriseLibrary.Logging.LogSource.TraceData(TraceEventType eventType, Int32 id, LogEntry logEntry, TraceListenerFilter traceListenerFilter)
at Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter.ProcessLog(LogEntry log)
at Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter.Write(LogEntry log)
at GraphPOC.EmailMain.<GetDataAsync>d__63.MoveNext()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(Action action, Boolean allowInlining, Task& currentTask)
at System.Threading.Tasks.Task.FinishContinuations()
at System.Threading.Tasks.Task`1.TrySetCanceled(CancellationToken tokenToRecord, Object cancellationException)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetException(Exception exception)
at Microsoft.Graph.MessageAttachmentsCollectionRequest.<GetAsync>d__3.MoveNext()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(Action action, Boolean allowInlining, Task& currentTask)
at System.Threading.Tasks.Task.FinishContinuations()
at System.Threading.Tasks.Task`1.TrySetCanceled(CancellationToken tokenToRecord, Object cancellationException)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetException(Exception exception)
at Microsoft.Graph.BaseRequest.<SendAsync>d__34`1.MoveNext()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(Action action, Boolean allowInlining, Task& currentTask)
at System.Threading.Tasks.Task.FinishContinuations()
at System.Threading.Tasks.Task`1.TrySetCanceled(CancellationToken tokenToRecord, Object cancellationException)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetException(Exception exception)
at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__40.MoveNext()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(Action action, Boolean allowInlining, Task& currentTask)
at System.Threading.Tasks.Task.FinishContinuations()
at System.Threading.Tasks.Task`1.TrySetCanceled(CancellationToken tokenToRecord, Object cancellationException)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetException(Exception exception)
at Microsoft.Graph.HttpProvider.<SendAsync>d__18.MoveNext()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(Action action, Boolean allowInlining, Task& currentTask)
at System.Threading.Tasks.Task.FinishContinuations()
at System.Threading.Tasks.Task`1.TrySetCanceled(CancellationToken tokenToRecord, Object cancellationException)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetException(Exception exception)
at Microsoft.Graph.HttpProvider.<SendRequestAsync>d__19.MoveNext()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(Action action, Boolean allowInlining, Task& currentTask)
at System.Threading.Tasks.Task.FinishContinuations()
at System.Threading.Tasks.Task`1.TrySetCanceled(CancellationToken tokenToRecord, Object cancellationException)
at System.Threading.Tasks.Task`1.TrySetCanceled(CancellationToken tokenToRecord)
at System.Threading.Tasks.TaskCompletionSource`1.TrySetCanceled(CancellationToken cancellationToken)
at System.Net.Http.HttpClient.SetTaskCanceled(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource, TaskCompletionSource`1 tcs)
at System.Net.Http.HttpClient.<>c__DisplayClass59_0.<StartContentBuffering>b__0(Task contentTask)
at System.Threading.Tasks.Task.Execute()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
at System.Threading.Tasks.Task.ExecuteEntry(Boolean bPreventDoubleExecution)
at System.Threading.Tasks.ThreadPoolTaskScheduler.TryExecuteTaskInline(Task task, Boolean taskWasPreviouslyQueued)
at System.Threading.Tasks.TaskScheduler.TryRunInline(Task task, Boolean taskWasPreviouslyQueued)
at System.Threading.Tasks.TaskContinuation.InlineIfPossibleOrElseQueue(Task task, Boolean needsProtection)
at System.Threading.Tasks.Task.FinishContinuations()
at System.Threading.Tasks.Task.Finish(Boolean bUserDelegateExecuted)
at System.Threading.Tasks.Task`1.TrySetException(Object exceptionObject)
at System.Threading.Tasks.TaskCompletionSource`1.TrySetException(Exception exception)
at System.Net.Http.HttpContent.<>c__DisplayClass21_0.<LoadIntoBufferAsync>b__0(Task copyTask)
at System.Threading.Tasks.Task.Execute()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
at System.Threading.Tasks.Task.ExecuteEntry(Boolean bPreventDoubleExecution)
at System.Threading.Tasks.ThreadPoolTaskScheduler.TryExecuteTaskInline(Task task, Boolean taskWasPreviouslyQueued)
at System.Threading.Tasks.TaskScheduler.TryRunInline(Task task, Boolean taskWasPreviouslyQueued)
at System.Threading.Tasks.TaskContinuation.InlineIfPossibleOrElseQueue(Task task, Boolean needsProtection)
at System.Threading.Tasks.Task.FinishContinuations()
at System.Threading.Tasks.Task.Finish(Boolean bUserDelegateExecuted)
at System.Threading.Tasks.Task`1.TrySetException(Object exceptionObject)
at System.Threading.Tasks.TaskCompletionSource`1.TrySetException(Exception exception)
at System.Net.Http.StreamToStreamCopy.BufferReadCallback(IAsyncResult ar)
at System.IO.Compression.DeflateStreamAsyncResult.Complete(Object result)
at System.IO.Compression.DeflateStream.ReadCallback(IAsyncResult baseStreamResult)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.ChunkParser.ReadCallback(IAsyncResult ar)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.FixedSizeReader.ReadCallback(IAsyncResult transportResult)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
Basically, when we use client credential flow to generate access token and use it to call the graph api, let's assume your "App1" had plenty of application api perissions like User.ReadWrite.All,Mail.ReadBasic.All,Files.ReadWrite.All, then the token will contain all these api permissions so that it can be used to search for users/mails/files. As you can see, this token will contain such a big permission.
Then go back to your scenario, you don't need to worry about the token overlapping because token just represent the authorization, since it contained correct api permission, then the token generated by each of your application can be used in other application because they all had the same configuration. In other words they are all valid.
About your exception, I'm not sure which line reported it, you may try to debug you code to find the problematic code. and I'm afraid it may relate to return Task.FromResult(0);. I searched for the error message and here's a question met the same error. Anyway it seems to be an unexpected task issue.
Since you are now using the graph client, I'm afraid you can call graph api directly without obtaining the access token first. Like code below:
var scopes = new[] { "https://graph.microsoft.com/.default" };
string tenantId = "TenantId";
string clientId = "ClientId";
string clientSecret = "ClientSecret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var user = await graphClient.Users.Request().GetAsync();

Converting mongoexport json to XML

I export data from our mongoDb database into json file, and need to parse it to XML in order to be usable in our ETL.
Here is a sample of code I try to use to parse one line of my json export :
var json = #"{""_id"":{""$oid"":""592bbd86b029e62830c5020a""},""DraftNumber"":""A1B1CB8D"",""ProductRange"":""COMPREHENSIVE_HOME_INSURANCE"",""DraftStatus"":""QUOTATION_DRAFT"",""DraftLabel"":"""",""LastUpdateDate"":{""$date"":""2017-05-29T06:19:53.559Z""},""EndDate"":{""$date"":""2017-07-28T06:19:53.559Z""},""UserId"":""D900036"",""ProjectNumber"":""38764496"",""Identifier"":"""",""CurrencyCode"":""EUR"",""RenewalDate"":{""$date"":""0001-01-01T00:00:00.000Z""},""RenewalDay"":0,""RenewalMounth"":0,""CreationDate"":{""$date"":""2017-05-29T06:19:50.138Z""},""EffectiveHour"":""0"",""EffectiveMinute"":""0"",""HasAs"":[{""_t"":""AgreementHolder"",""_id"":{""$oid"":""000000000000000000000000""},""DistribCustomer"":{""isProspect"":true}}],""IsBasedOnProduct"":{""pricingType"":""DISCOUNT_RATE"",""pricingVersion"":""C""},""ActivityInAgreements"":[{""_t"":""AgreementRequest"",""_id"":{""$oid"":""000000000000000000000000""},""PremiumNature"":null}],""OriginalSubscriptionChannel"":""DIRECT"",""CurrentSubscriptionChannel"":""DIRECT"",""BusinessExpirationDate"":{""$date"":""0001-01-01T00:00:00.000Z""},""TechnicalExpirationDate"":{""$date"":""2017-08-27T06:19:53.559Z""},""IsEligibleToProposal"":true,""IneligibityReasonCodes"":[],""DematerialisationOfDocuments"":true}";
var doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
Console.WriteLine(doc);
Console.ReadKey();
And i face the following exception :
L'exception Newtonsoft.Json.JsonSerializationException n'a pas été
gérée HResult=-2146233088 Message=JSON root object has multiple
properties. The root object must have a single property in order to
create a valid XML document. Consider specifying a
DeserializeRootElementName. Path 'DraftNumber', line 1, position 57.
Source=Newtonsoft.Json StackTrace:
à Newtonsoft.Json.Converters.XmlNodeConverter.DeserializeNode(JsonReader
reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode
currentNode)
à Newtonsoft.Json.Converters.XmlNodeConverter.ReadJson(JsonReader
reader, Type objectType, Object existingValue, JsonSerializer
serializer)
à Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter
converter, JsonReader reader, Type objectType, Object existingValue)
à Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader
reader, Type objectType, Boolean checkAdditionalContent)
à Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
à Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
à Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonConverter[] converters)
à Newtonsoft.Json.JsonConvert.DeserializeXmlNode(String value, String deserializeRootElementName, Boolean writeArrayAttribute)
à Newtonsoft.Json.JsonConvert.DeserializeXmlNode(String value)
à ConsoleApplication3.Program.Main(String[] args) dans c:\documents\s638723\documents\visual studio
2015\Projects\ConsoleApplication3\Program.cs:ligne 17
à System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
à System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
à System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ThreadHelper.ThreadStart() InnerException:
More globally i'm wondering if the type exported by mongoexport is usable by the jsonconverter.
As the exception states, JSON has multiple properties at top level.
Simply define root like:
using (StreamReader r = new StreamReader("Json_1.json"))
{
string json = r.ReadToEnd();
var doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json, "root");
}
Output:
<root>
<_id>
<_x0024_oid>592bbd86b029e62830c5020a</_x0024_oid>
</_id>
<DraftNumber>A1B1CB8D</DraftNumber>
<ProductRange>COMPREHENSIVE_HOME_INSURANCE</ProductRange>
<DraftStatus>QUOTATION_DRAFT</DraftStatus>
<DraftLabel/>
<LastUpdateDate>
<_x0024_date>2017-05-29T06:19:53.559Z</_x0024_date>
</LastUpdateDate>
<EndDate>
<_x0024_date>2017-07-28T06:19:53.559Z</_x0024_date>
</EndDate>
<UserId>D900036</UserId>
<ProjectNumber>38764496</ProjectNumber>
<Identifier/>
<CurrencyCode>EUR</CurrencyCode>
<RenewalDate>
<_x0024_date>0001-01-01T00:00:00Z</_x0024_date>
</RenewalDate>
<RenewalDay>0</RenewalDay>
<RenewalMounth>0</RenewalMounth>
<CreationDate>
<_x0024_date>2017-05-29T06:19:50.138Z</_x0024_date>
</CreationDate>
<EffectiveHour>0</EffectiveHour>
<EffectiveMinute>0</EffectiveMinute>
<HasAs>
<_t>AgreementHolder</_t>
<_id>
<_x0024_oid>000000000000000000000000</_x0024_oid>
</_id>
<DistribCustomer>
<isProspect>true</isProspect>
</DistribCustomer>
</HasAs>
<IsBasedOnProduct>
<pricingType>DISCOUNT_RATE</pricingType>
<pricingVersion>C</pricingVersion>
</IsBasedOnProduct>
<ActivityInAgreements>
<_t>AgreementRequest</_t>
<_id>
<_x0024_oid>000000000000000000000000</_x0024_oid>
</_id>
<PremiumNature />
</ActivityInAgreements>
<OriginalSubscriptionChannel>DIRECT</OriginalSubscriptionChannel>
<CurrentSubscriptionChannel>DIRECT</CurrentSubscriptionChannel>
<BusinessExpirationDate>
<_x0024_date>0001-01-01T00:00:00Z</_x0024_date>
</BusinessExpirationDate>
<TechnicalExpirationDate>
<_x0024_date>2017-08-27T06:19:53.559Z</_x0024_date>
</TechnicalExpirationDate>
<IsEligibleToProposal>true</IsEligibleToProposal>
<DematerialisationOfDocuments>true</DematerialisationOfDocuments>
</root>

Subclassing DataTable

I'm using Entity Framework and a stored proc that takes a table valued parameter (TVP). To do this, I need to create a DataTable and populate it like so:
var i = new DataTable();
i.Columns.Add("Type", typeof(byte));
i.Columns.Add("Code", typeof(int));
i.Rows.Add(0, 0);
i.Rows.Add(2, 31);
i.Rows.Add(4, 3121);
i.Rows.Add(4, 3111);
And then I can pass it as a parameter to a call to SqlQuery
var result = ctx.Database.SqlQuery<MyResult>("select * from myStoredProc(#i)",
new SqlParameter("#i",i) { TypeName = "MyTVP" });
Now to simplify this, especially recreating the columns every time, I though I could subclass DataTable, something like this:
public class MyTVP : DataTable
{
public MyTVP()
: base()
{
Columns.Add("Type", typeof(byte));
Columns.Add("Code", typeof(int));
}
}
So now my code to create and populate the table is this:
var i = new MyTVP();
i.Rows.Add(0, 0);
i.Rows.Add(2, 31);
i.Rows.Add(4, 3121);
i.Rows.Add(4, 3111);
But if I try to pass this as a parameter to the stored proc I get an ArgumentException:
No mapping exists from object type MyTVP to a known managed provider native type.
Is there a way to subclass DataTable such that you can pass it to the stored proc?
I worked around this problem by having MyTVP wrap a DataTable instead and then have a property that exposes the DataTable, but it's a little messy.
Stacktrace:
at System.Data.SqlClient.MetaType.GetMetaTypeFromValue(Type dataType, Object value, Boolean inferLen, Boolean streamAllowed)
at System.Data.SqlClient.SqlParameter.GetMetaTypeOnly()
at System.Data.SqlClient.SqlParameter.get_DbType()
at System.Data.Entity.Infrastructure.Interception.DatabaseLogFormatter.LogParameter[TResult](DbCommand command, DbCommandInterceptionContext`1 interceptionContext, DbParameter parameter)
at System.Data.Entity.Infrastructure.Interception.DatabaseLogFormatter.LogCommand[TResult](DbCommand command, DbCommandInterceptionContext`1 interceptionContext)
at System.Data.Entity.Infrastructure.Interception.DatabaseLogFormatter.Executing[TResult](DbCommand command, DbCommandInterceptionContext`1 interceptionContext)
at System.Data.Entity.Infrastructure.Interception.DatabaseLogFormatter.ReaderExecuting(DbCommand command, DbCommandInterceptionContext`1 interceptionContext)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__d(IDbCommandInterceptor i, DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass65`1.<ExecuteStoreQueryReliably>b__64()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass65`1.<ExecuteStoreQueryReliably>b__63()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClass14`1.<ExecuteSqlQuery>b__13()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at ConsoleApplication2.Program.Main(String[] args) in c:\Users\matt.burland\Documents\Visual Studio 2013\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 72
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Try changing the parameter to:
new SqlParameter("#i", i) { TypeName = "MyTVP", SqlDbType = SqlDbType.Structured }
Another option would be instead of creating a new type create a DataTable factory that create the datatables with the right columns on it.

How to know which piece of code is the cause of an exception?

How is it possible to know which piece of code could cause the exception 'SPException was unhandled'?
CODE:
SPList mylist = web.Lists.TryGetList("mylist");
SPListItem item = mylist.Items.Add();
... ... ...
item.Update();
The trace is:
Stack details:
at Microsoft.SharePoint.SPGlobal.HandleComException(COMException comEx)
at Microsoft.SharePoint.Library.SPRequest.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bPreserveItemUIVersion, Boolean bUpdateNoVersion, Int32& plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, Boolean bUnRestrictedUpdateInProgress, Boolean bMigration, Boolean bPublish, String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback)
at Microsoft.SharePoint.SPListItem.AddOrUpdateItem(Boolean bAdd, Boolean bSystem, Boolean bPreserveItemVersion, Boolean bNoVersion, Boolean bMigration, Boolean bPublish, Boolean bCheckOut, Boolean bCheckin, Guid newGuidOnAdd, Int32& ulID, Object& objAttachmentNames, Object& objAttachmentContents, Boolean suppressAfterEvents, String filename, Boolean bPreserveItemUIVersion)
at Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem, Boolean bPreserveItemVersion, Guid newGuidOnAdd, Boolean bMigration, Boolean bPublish, Boolean bNoVersion, Boolean bCheckOut, Boolean bCheckin, Boolean suppressAfterEvents, String filename, Boolean bPreserveItemUIVersion)
at Microsoft.SharePoint.SPListItem.Update()
at Dumper.Program.Main(String[] args) in c:\users\svcspfarm\documents\visual studio 2010\Projects\Dumper\Dumper\Program.cs:line 364
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Look the sharepoint ULS logs to find out more information about exception.
\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS
For me it looks like you have not setup values for the required list fields.
Have a look at these lines from stack trace:
at Microsoft.SharePoint.SPListItem.Update()
at Dumper.Program.Main(String[] args) in c:\users\svcspfarm\documents\visual studio 2010\Projects\Dumper\Dumper\Program.cs:line 364
The exception is occurring on the call to item.Update();. I had a similar problem when I was attempting to add a subfolder to a list and it can be less than obvious what is causing the problem. I would hazard a guess that somewhere between your call to mylist.Items.Add(); and the Update() that something has not been set correctly. A new list item may have some required fields that need to be initialised prior to the update?

LINQ to Entities returning "Object reference not set to an instance of an object."

I have a piece of code that checks to see if a user is in our database using a view called RESOURCE_V. If not, the code uses Entity Framework to add the user to the database using the user's information from Active Directory. I would then like to re-query the RESOURCE_V view to get the submitted information. Upon doing so I am getting "Object reference not set to an instance of an object.". Here is the full code:
HALEntities context = new HALEntities();
List<RESOURCE_V> userData = (from i in context.RESOURCE_V
where i.NT_USER_N == Environment.UserName
select i).ToList();
// add user to RSRC table using Active Directory details
if (userData.Count > 0)
{
PrincipalContext principleContext = new PrincipalContext(ContextType.Domain, HAL_Globals.domain);
UserPrincipal user = UserPrincipal.FindByIdentity(principleContext, IdentityType.SamAccountName, HAL_Globals.domain + "\\" + Environment.UserName);
RSRC rsrc = new RSRC();
rsrc.RSRC_I = context.RSRCs.Select(u => u.RSRC_I).Max() + 1;
rsrc.NT_USER_N = user.SamAccountName + "AAAA";
rsrc.FRST_N = user.GivenName;
rsrc.LAST_N = user.Surname;
rsrc.INIL_N = (user.MiddleName == null) ? "X" : user.MiddleName.Substring(0, 1);
rsrc.SHRT_N = user.GivenName.Substring(0, 1) + ((user.MiddleName == null) ? "X" : user.MiddleName.Substring(0, 1)) + user.Surname.Substring(0, 1);
rsrc.EMAIL_I = user.EmailAddress;
rsrc.TELE_I = user.VoiceTelephoneNumber.Replace("(", "").Replace(")", "").Replace("-", "");
rsrc.ACTV_F = true;
rsrc.CRTE_USER_I = Environment.UserName;
rsrc.CRTE_TS = DateTime.Now;
rsrc.UPDT_USER_I = Environment.UserName;
rsrc.UPDT_TS = DateTime.Now;
context.RSRCs.Add(rsrc);
context.SaveChanges();
userData = (from i in context.RESOURCE_V
where i.NT_USER_N == Environment.UserName + "AAAA"
select i).ToList();
}
Notice the logic doesn't exactly match my description as I am using this code to test against my ID that already exists. The line that errors out is the very last statement in the if block:
userData = (from i in context.RESOURCE_V
where i.NT_USER_N == Environment.UserName + "AAAA"
select i).ToList();
I have tried recreating the Entity context, using different LINQ syntax, but have had no luck. Any help would be appreciated.
Edit:
As requested, here is the stack trace:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at System.Xaml.Schema.SafeReflectionInvoker.CreateInstanceCritical(Type type, Object[] arguments)
at System.Xaml.Schema.SafeReflectionInvoker.CreateInstance(Type type, Object[] arguments)
at System.Xaml.Schema.XamlTypeInvoker.CreateInstance(Object[] arguments)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstanceWithCtor(XamlType xamlType, Object[] args)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)
at MS.Internal.Xaml.Runtime.PartialTrustTolerantRuntime.CreateInstance(XamlType xamlType, Object[] args)
at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.WriteStartMember(XamlMember property)
at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
at System.Windows.Application.DoStartup()
at System.Windows.Application.<.ctor>b__1(Object unused)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at HAL.App.Main() in c:\HAL\HAL_PROD\HAL\obj\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
at System.Activator.CreateInstance(ActivationContext activationContext)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Edit 2: The Inner Exception Stack Trace:
at System.Data.EntityKey.AddHashValue(Int32 hashCode, Object keyValue)
at System.Data.EntityKey.GetHashCode()
at System.Collections.Generic.GenericEqualityComparer`1.GetHashCode(T obj)
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
at System.Data.Objects.ObjectStateManager.TryGetEntityEntry(EntityKey key, EntityEntry& entry)
at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
at lambda_method(Closure , Shaper )
at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at HAL.HAL_CurrentUser..ctor(SqlConnection currentServerConnection) in c:\HAL\HAL_PROD\HAL\Global Classes\HAL_CurrentUser.cs:line 86
at HAL.HAL_CurrentUser.get_Instance() in c:\HAL\HAL_PROD\HAL\Global Classes\HAL_CurrentUser.cs:line 46
at HAL.WelcomeViewModel..ctor() in c:\HAL\HAL_PROD\HAL\HAL Classes\Welcome\WelcomeViewModel.cs:line 21
at HAL.Welcome..ctor() in c:\HAL\HAL_PROD\HAL\HAL Classes\Welcome\Welcome.xaml.cs:line 26
at HAL.Navigation..ctor() in c:\HAL\HAL_PROD\HAL\Navigation.xaml.cs:line 17
Edit 3:
After playing around with the values being queried in the second LINQ query I have determined the issue is being caused by the fact that I am filtering on the new ID in the where clause of the LINQ query. If I hard-code another ID in the query it works and the error is not thrown. I have determined the new ID is in fact being added to the database.
The entity has a composite key and when you save the new entity one of the key column is null. EF does not support nullable keys (it throws) but apparently there is a bug in EF where this condition is not checked in this specific scenario and hence the NRE. You need to make sure that you are not returning null values in primary key columns.
I had the same problem. My class field of collection type was empty. I struggled a lot to fix the problem.
Finally the error was in typo - I was creating the object with new while making local declaration for the class field name and then it was going out of local scope.
I know that it doesn't answer the topic, but as a point to re-check the code for such errors.
Sorry, I really wanted to help other guys like me with the similar problem.

Categories