How to enable $expand and $select on ODataQueryOptions? - c#

The issue started here, where I am unable to call $select or $expand on results.
Given:
var results = options.ApplyTo(_uow.Repository<ContentType>()
.Query()
.Get()
.Include(u => u.User)
.Where(u => u.UserId == userId)
.OrderBy(o => o.Description)).Cast<ContentType>()
.Select(x => new ContentTypeDTO()
{
//projection goes here
ContentTypeId = x.ContentTypeId,
Description = x.Description,
UserDTO = new UserDTO
{
UserId = x.UserId,
UserName = x.User.UserName
}
});
Exception:
Unable to cast the type
'System.Web.Http.OData.Query.Expressions.SelectExpandBinder+SelectSome`1[[Project.DAL.Data.Models.ContentType,
Project.DAL.Data, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]]' to type 'Project.DAL.Data.Models.ContentType'.
LINQ to Entities only supports casting EDM primitive or enumeration
types."
Based on this solution, I understand that when $select or $expand are applied to the result, it is no longer a ContentType, as is expected by the Cast<ContentType>(). That solution uses HierarchyNodeExpressionVisitor, which I am unable to locate.
I want to use 'options.ApplyTo()' as I want the filtering done on the db server, to ensure I don't get back an inflated data set with hundreds of thousands of rows.
Is there a suggested way of getting around this?
-- UPDATE --
In using #Schandlich 's suggested solution below, the operation still fails with the Ok override:
Locals:
+ this {Project.AdminWebsite.Api.Controllers.ContentTypeController} Project.AdminWebsite.Api.Controllers.ODataBaseController {Project.AdminWebsite.Api.Controllers.ContentTypeController}
+ content {System.Data.Entity.Infrastructure.DbQuery<Project.Core.UI.Models.ContentTypeDTO>} object {System.Data.Entity.Infrastructure.DbQuery<Project.Core.UI.Models.ContentTypeDTO>}
+ type {Name = "DbQuery`1" FullName = "System.Data.Entity.Infrastructure.DbQuery`1[[Project.Core.UI.Models.ContentTypeDTO, Project.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"} System.Type {System.RuntimeType}
+ resultType {Name = "OkNegotiatedContentResult`1" FullName = "System.Web.Http.Results.OkNegotiatedContentResult`1[[System.Data.Entity.Infrastructure.DbQuery`1[[Project.Core.UI.Models.ContentTypeDTO, Project.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"} System.Type {System.RuntimeType}
+ result {System.Web.Http.Results.OkNegotiatedContentResult<System.Data.Entity.Infrastructure.DbQuery<Project.Core.UI.Models.ContentTypeDTO>>} System.Web.Http.IHttpActionResult {System.Web.Http.Results.OkNegotiatedContentResult<System.Data.Entity.Infrastructure.DbQuery<Project.Core.UI.Models.ContentTypeDTO>>}
Call stack:
> Project.AdminWebsite.dll!Project.AdminWebsite.Api.Controllers.ODataBaseController.Ok(object content, System.Type type) Line 27 C#
Project.AdminWebsite.dll!Project.AdminWebsite.Api.Controllers.ContentTypeController.Get(System.Web.Http.OData.Query.ODataQueryOptions<Project.DAL.Data.Models.ContentType> odataQueryOptions) Line 132 C#
[Lightweight Function]
System.Web.Http.dll!System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.GetExecutor.AnonymousMethod__9(object instance, object[] methodParameters) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(object instance, object[] arguments) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Collections.Generic.IDictionary<string,object> arguments, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpActionDescriptorTracer.ExecuteAsync.AnonymousMethod__1() Unknown
System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync<object>(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action<System.Web.Http.Tracing.TraceRecord> beginTrace, System.Func<System.Threading.Tasks.Task<object>> execute, System.Action<System.Web.Http.Tracing.TraceRecord,object> endTrace, System.Action<System.Web.Http.Tracing.TraceRecord> errorTrace) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpActionDescriptorTracer.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Collections.Generic.IDictionary<string,object> arguments, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore() Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore>(ref System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore>(ref System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpActionInvokerTracer.System.Web.Http.Controllers.IHttpActionInvoker.InvokeActionAsync.AnonymousMethod__1() Unknown
System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync<System.Net.Http.HttpResponseMessage>(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action<System.Web.Http.Tracing.TraceRecord> beginTrace, System.Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> execute, System.Action<System.Web.Http.Tracing.TraceRecord,System.Net.Http.HttpResponseMessage> endTrace, System.Action<System.Web.Http.Tracing.TraceRecord> errorTrace) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpActionInvokerTracer.System.Web.Http.Controllers.IHttpActionInvoker.InvokeActionAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ActionFilterResult.ActionInvoker.InvokeActionAsync() Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync() Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync>(ref System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync>(ref System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync(System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.ApiController.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore() Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore>(ref System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore>(ref System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpControllerTracer.System.Web.Http.Controllers.IHttpController.ExecuteAsync.AnonymousMethod__0() Unknown
System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync<System.Net.Http.HttpResponseMessage>(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action<System.Web.Http.Tracing.TraceRecord> beginTrace, System.Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> execute, System.Action<System.Web.Http.Tracing.TraceRecord,System.Net.Http.HttpResponseMessage> endTrace, System.Action<System.Web.Http.Tracing.TraceRecord> errorTrace) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpControllerTracer.System.Web.Http.Controllers.IHttpController.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync() Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync>(ref System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync>(ref System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.AnonymousMethod__FabricatedMethod6() Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.SendAsync.AnonymousMethod__1() Unknown
System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync<System.Net.Http.HttpResponseMessage>(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action<System.Web.Http.Tracing.TraceRecord> beginTrace, System.Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> execute, System.Action<System.Web.Http.Tracing.TraceRecord,System.Net.Http.HttpResponseMessage> endTrace, System.Action<System.Web.Http.Tracing.TraceRecord> errorTrace) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.HttpServer.AnonymousMethod__FabricatedMethod9() Unknown
System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync() Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<System.Web.Http.HttpServer.SendAsync>(ref System.Web.Http.HttpServer.SendAsync stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.HttpServer.SendAsync>(ref System.Web.Http.HttpServer.SendAsync stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.WebHost.dll!System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore() Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore>(ref System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore>(ref System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore stateMachine) Unknown
System.Web.Http.WebHost.dll!System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore(System.Web.HttpContextBase contextBase) Unknown
System.Web.Http.WebHost.dll!System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsync(System.Web.HttpContext context) Unknown
System.Web.dll!System.Web.HttpTaskAsyncHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest.AnonymousMethod__0() Unknown
System.Web.dll!System.Web.TaskAsyncHelper.BeginTask(System.Func<System.Threading.Tasks.Task> taskFunc, System.AsyncCallback callback, object state) Unknown
System.Web.dll!System.Web.HttpTaskAsyncHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(System.Web.HttpContext context, System.AsyncCallback cb, object extraData) Unknown
System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() Unknown
System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step, ref bool completedSynchronously) Unknown
System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error) Unknown
System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext context, System.AsyncCallback cb) Unknown
System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr, System.Web.HttpContext context) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
[Native to Managed Transition]
[Managed to Native Transition]
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
[AppDomain Transition]
Error Message:
Unable to cast the type 'System.Web.Http.OData.Query.Expressions.SelectExpandBinder+SelectAll`1[[Project.DAL.Data.Models.ContentType, Project.DAL.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' to type 'Project.DAL.Data.Models.ContentType'. LINQ to Entities only supports casting EDM primitive or enumeration types.

From $select and $expand break ODataQueryOptions -- how to fix?
public IHttpActionResult Get(ODataQueryOptions<YourEntity> odataQueryOptions)
{
//Your applyTo logic and results.
if (odataQueryOptions.SelectExpand != null)
{
Request.SetSelectExpandClause(odataQueryOptions.SelectExpand.SelectExpandClause);
}
return Ok(results, results.GetType());
}
private IHttpActionResult Ok(object content, Type type)
{
Type resultType = typeof(OkNegotiatedContentResult<>).MakeGenericType(type);
return Activator.CreateInstance(resultType, content, this) as IHttpActionResult;
}
But as I stated in your other question, keep looking for ways to avoid manually applying the results if you can.

Related

Entity Framework attempting to add records to wrong table [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I have never had an issue with Entity Framework attempting to save to the wrong table before. However, today I've run into this issue.
I am attempting to save to a table called dbo.Accounts in SQL Server and for some strange reason, the SQL that it creates is the following.
DECLARE #inserted0 TABLE ([Id] int, [_Position] [int]);
MERGE [Accounts] USING (
VALUES (#p0, #p1, #p2, #p3, 0),
(#p4, #p5, #p6, #p7, 1),
(#p8, #p9, #p10, #p11, 2)) AS i ([CreateDate], [LastUpdated], [Name], [ParentId], _Position) ON 1=0
WHEN NOT MATCHED THEN
INSERT ([CreateDate], [LastUpdated], [Name], [ParentId])
VALUES (i.[CreateDate], i.[LastUpdated], i.[Name], i.[ParentId])
OUTPUT INSERTED.[Id], i._Position
INTO #inserted0;
SELECT [i].[Id] FROM #inserted0 i
ORDER BY [i].[_Position];
INSERT INTO [AspNetUserRoles] ([RoleId], [UserId])
VALUES (#p12, #p13);
',N'#p0 datetime2(7),#p1 datetime2(7),#p2 nvarchar(100),#p3 int,#p4 datetime2(7),#p5 datetime2(7),#p6 nvarchar(100),#p7 int,#p8 datetime2(7),#p9 datetime2(7),#p10 nvarchar(100),#p11 int,#p12 nvarchar(450),#p13 nvarchar(450)',#p0='2022-01-27 11:19:59.5774258',#p1='2022-01-27 11:19:59.5774300',#p2=N'Test Account',#p3=1,#p4='2022-01-27 11:24:37.7412127',#p5='2022-01-27 11:24:37.7412136',#p6=N'test',#p7=1,#p8='2022-01-27 11:28:45.9794153',#p9='2022-01-27 11:28:45.9794169',#p10=N'test',#p11=1,#p12=N'5d0f3665-110a-4986-9bbf-3f2b7da0ccbf',#p13=N'db9f3ebb-3e0d-4972-a8f9-c7cdb10ed94f'
As you can see it's attempting to save the account, AND trying to create a UserRole.
The exception is the following:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (39ms) [Parameters=[#p0='?' (Size = 450), #p1='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
INSERT INTO [AspNetUserRoles] ([RoleId], [UserId])
VALUES (#p0, #p1);
fail: Microsoft.EntityFrameworkCore.Update[10000]
An exception occurred in the database while saving changes for context type 'PipelineSolutions.DataAccess.ApplicationDbContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AspNetUserRoles_AspNetUsers_UserId". The conflict occurred in database "PipelineSolutions", table "dbo.AspNetUsers", column 'Id'.
The statement has been terminated.
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__188_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken) ClientConnectionId:dddf9058-bb37-477b-8a67-20b506e4efde
Error Number:547,State:0,Class:16
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AspNetUserRoles_AspNetUsers_UserId". The conflict occurred in database "PipelineSolutions", tab
le "dbo.AspNetUsers", column 'Id'.
The statement has been terminated.
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__188_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
ClientConnectionId:dddf9058-bb37-477b-8a67-20b506e4efde
Error Number:547,State:0,Class:16
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AspNetUserRoles_AspNetUsers_UserId". The conflict occurred in database "PipelineSolutions", tab
le "dbo.AspNetUsers", column 'Id'.
The statement has been terminated.
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__188_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
ClientConnectionId:dddf9058-bb37-477b-8a67-20b506e4efde
Error Number:547,State:0,Class:16
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at PipelineSolutions.DataAccess.Repository.AccountsRepository.CreateAsync(Account entity, CancellationToken token) in C:\Users\James\source\repos\PiplelineSolutions\Server\PipelineSolutions.DataAccess\Repository\Accoun
tsRepository.cs:line 40
at PipelineSolutions.Controllers.Identity.AccountsController.Post(Account account, CancellationToken token) in C:\Users\James\source\repos\PiplelineSolutions\Server\PipelineSolutions\Controllers\Identity\AccountsContro
ller.cs:line 38
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted
)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at PipelineSolutions.Middleware.UserClaimsMiddleware.InvokeAsync(HttpContext context, UserManager`1 userManager) in C:\Users\James\source\repos\PiplelineSolutions\Server\PipelineSolutions\Middleware\UserClaimsMiddlewar
e.cs:line 37
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
fail: Microsoft.EntityFrameworkCore.Update[10000]
An exception occurred in the database while saving changes for context type 'PipelineSolutions.DataAccess.ApplicationDbContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AspNetUserRoles_AspNetUsers_UserId". The conflict occurred in database "PipelineSolutions", tab
le "dbo.AspNetUsers", column 'Id'.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
at Microsoft.Data.SqlClient.SqlDataReader.TryHasMoreResults(Boolean& moreResults)
at Microsoft.Data.SqlClient.SqlDataReader.TryNextResult(Boolean& more)
at Microsoft.Data.SqlClient.SqlDataReader.NextResultAsyncExecute(Task task, Object state)
at Microsoft.Data.SqlClient.SqlDataReader.InvokeAsyncCall[T](AAsyncCallContext`1 context)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
ClientConnectionId:dddf9058-bb37-477b-8a67-20b506e4efde
Error Number:547,State:0,Class:16
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AspNetUserRoles_AspNetUsers_UserId". The conflict occurred in database "PipelineSolutions", tab
le "dbo.AspNetUsers", column 'Id'.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
at Microsoft.Data.SqlClient.SqlDataReader.TryHasMoreResults(Boolean& moreResults)
at Microsoft.Data.SqlClient.SqlDataReader.TryNextResult(Boolean& more)
at Microsoft.Data.SqlClient.SqlDataReader.NextResultAsyncExecute(Task task, Object state)
at Microsoft.Data.SqlClient.SqlDataReader.InvokeAsyncCall[T](AAsyncCallContext`1 context)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
ClientConnectionId:dddf9058-bb37-477b-8a67-20b506e4efde
Error Number:547,State:0,Class:16
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
And the code that I am calling:
// Repository
public override async Task<Account> CreateAsync (Account entity, CancellationToken token)
{
entity.CreateDate = DateTime.Now;
entity.LastUpdated = DateTime.Now;
if (entity.ParentId == 0)
entity.ParentId = 1;
Context.Accounts.Add(entity);
var a = await Context.SaveChangesAsync(token);
return entity;
}
// ApplicationDbContext
public virtual DbSet<Account>? Accounts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Account>()
.HasMany(x => x.ChildAccounts)
.WithOne(x => x.Parent);
modelBuilder.Entity<Account>()
.Property(x => x.ParentId)
.IsRequired(false);
//... other configuration
}
// model
[Table("Accounts", Schema = "dbo")]
public class Account:BaseEntity
{
[StringLength(100), Required]
public string Name { get; set; }
public int? ParentId { get; set; }
public Account? Parent { get; set; }
public ICollection<Account>? ChildAccounts { get; set; }
}
Why would this happen with only accounts, all of the other entities work correctly? Is there something in the name Account that is causing this issue?
**Update**
In the `ChangeTracker.DebugView` I see this:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/VjmFW.png
[HttpPost]
public virtual async Task<IActionResult> Post(T model, CancellationToken token)
{
try
{
if (model is IOwner owner)
{
UpdateOwnerId(owner);
}
if (model.AccountId == 0)
{
model.AccountId = AccountId;
}
var response = await Repository.CreateAsync(model, token);
return Ok(response);
}
catch (Exception e)
{
Logger.LogError(e, e.Message);
throw;
}
}

Mongodb C# driver An exception occurred while sending a message to the server

I got below exception while try to update data in mongodb. Please help me to fix this issue.
When I look in my logs I see lot of error messages just like the one below where the driver is getting a socket error when connecting to mongo. The site is still up and this error doesn't happen on every request, nor does it happen on one operation that should take longer.
The version I have used C# driver : "2.10.2" and Azure Cosmos version :3.6".
MongoDB.Driver.MongoConnectionException: An exception occurred while sending a message to the server. ---> System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Security._SslStream.StartWriting(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.ProcessWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MongoDB.Driver.Core.Misc.StreamExtensionMethods.WriteBytes(Stream stream, IByteBuffer buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Connections.BinaryConnection.SendBuffer(IByteBuffer buffer, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at MongoDB.Driver.Core.Connections.BinaryConnection.SendBuffer(IByteBuffer buffer, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Connections.BinaryConnection.SendMessages(IEnumerable1 messages, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken) at MongoDB.Driver.Core.ConnectionPools.ExclusiveConnectionPool.AcquiredConnection.SendMessages(IEnumerable1 messages, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Connections.ConnectionExtensions.SendMessage(IConnection connection, RequestMessage message, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)
at MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol1.Execute(IConnection connection, CancellationToken cancellationToken) at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol1.Execute(IConnection connection, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Servers.Server.ServerChannel.ExecuteProtocol[TResult](IWireProtocol1 protocol, ICoreSession session, CancellationToken cancellationToken) at MongoDB.Driver.Core.Servers.Server.ServerChannel.Command[TResult](ICoreSession session, ReadPreference readPreference, DatabaseNamespace databaseNamespace, BsonDocument command, IEnumerable1 commandPayloads, IElementNameValidator commandValidator, BsonDocument additionalOptions, Action1 postWriteAction, CommandResponseHandling responseHandling, IBsonSerializer1 resultSerializer, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.RetryableWriteCommandOperationBase.ExecuteAttempt(RetryableWriteContext context, Int32 attempt, Nullable1 transactionNumber, CancellationToken cancellationToken) at MongoDB.Driver.Core.Operations.RetryableWriteOperationExecutor.Execute[TResult](IRetryableWriteOperation1 operation, RetryableWriteContext context, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.BulkUnmixedWriteOperationBase1.ExecuteBatch(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken) at MongoDB.Driver.Core.Operations.BulkUnmixedWriteOperationBase1.ExecuteBatches(RetryableWriteContext context, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.BulkUnmixedWriteOperationBase1.Execute(RetryableWriteContext context, CancellationToken cancellationToken) at MongoDB.Driver.Core.Operations.BulkMixedWriteOperation.ExecuteBatch(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken) at MongoDB.Driver.Core.Operations.BulkMixedWriteOperation.Execute(IWriteBinding binding, CancellationToken cancellationToken) at MongoDB.Driver.OperationExecutor.ExecuteWriteOperation[TResult](IWriteBinding binding, IWriteOperation1 operation, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.ExecuteWriteOperation[TResult](IClientSessionHandle session, IWriteOperation1 operation, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.BulkWrite(IClientSessionHandle session, IEnumerable1 requests, BulkWriteOptions options, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.<>c__DisplayClass23_0.<BulkWrite>b__0(IClientSessionHandle session) at MongoDB.Driver.MongoCollectionImpl1.UsingImplicitSession[TResult](Func2 func, CancellationToken cancellationToken) at MongoDB.Driver.MongoCollectionImpl1.BulkWrite(IEnumerable1 requests, BulkWriteOptions options, CancellationToken cancellationToken) at MongoDB.Driver.MongoCollectionBase1.<>c__DisplayClass92_0.b__0(IEnumerable1 requests, BulkWriteOptions bulkWriteOptions) at MongoDB.Driver.MongoCollectionBase1.UpdateMany(FilterDefinition1 filter, UpdateDefinition1 update, UpdateOptions options, Func3 bulkWrite) at MongoDB.Driver.MongoCollectionBase1.UpdateMany(FilterDefinition1 filter, UpdateDefinition1 update, UpdateOptions options, CancellationToken cancellationToken)
at Sensiple.Tryvium.Data.MongoDB.CommonConnector.Update(String schemaName, String dataFilter, String data, String logSource)
Code that causes issue,
var _collection = Db.GetCollection<BsonDocument>(schemaName);
BsonDocument bsonDocument = new BsonDocument(BsonSerializer.Deserialize<BsonDocument>(dataFilter));
var updatedResult = _collection.UpdateMany(bsonDocument, BsonDocument.Parse("{$set: " + BsonSerializer.Deserialize<BsonDocument>(data) + "}"));
I had the exact same issue (which probably started when we upgraded from Cosmos 3.2 to 3.6/4.0), and the fix was to set/force TLS 1.2 (based on this Microsoft document):
//return new MongoClient(connectionString);
var settings = MongoClientSettings.FromConnectionString(connectionString);
settings.SslSettings = new SslSettings()
{
EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12
};
return new MongoClient(settings);

Failed executing DbCommand. .NET CORE

During creating my first page I noticed that I could not run .Net from cmd. I do not know what exactly is a problem. I am sending you a command lines.
I checked some website's solutions. None from this solutions helped me.
C:\Users\prywatny\Desktop\ProjektodZera\BigProject\BigProject>dotnet ef database update
Done.
C:\Users\prywatny\Desktop\ProjektodZera\BigProject\BigProject>dotnet run
Używanie ustawień uruchamiania z profilu C:\Users\prywatny\Desktop\ProjektodZera\BigProject\BigProject\Properties\launchSettings.json...
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (133ms) [Parameters=[#__normalizedEmail_0='?' (Size = 256)], CommandType='Text', CommandTimeout='30']
SELECT TOP(1) [u].[Id], [u].[AccessFailedCount], [u].[ConcurrencyStamp], [u].[Email], [u].[EmailConfirmed], [u].[FirstName], [u].[LastName], [u].[LockoutEnabled], [u].[LockoutEnd], [u].[NormalizedEmail], [u].[NormalizedUserName], [u].[PasswordHash], [u].[PhoneNumber], [u].[PhoneNumberConfirmed], [u].[SecurityStamp], [u].[TwoFactorEnabled], [u].[UserName]
FROM [AspNetUsers] AS [u]
WHERE [u].[NormalizedEmail] = #__normalizedEmail_0
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'AspNetUsers'.
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__122_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues, CancellationToken cancellationToken)
ClientConnectionId:68090395-2d00-4ce7-9f2b-0ed6813b9694
Error Number:208,State:1,Class:16
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred in the database while iterating the results of a query for context type 'BigProject.Data.Context'.
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'AspNetUsers'.
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__122_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 para
Unhandled Exception: meterValues, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.FirstOrDefault_[TSource](IAsyncEnumerable`1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable`1.Enumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.MoveNextCore(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.AsyncIterator`1.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)
ClientConnectionId:68090395-2d00-4ce7-9f2b-0ed6813b9694
Error Number:208,State:1,Class:16
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'AspNetUsers'.
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__122_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.FirstOrDefault_[TSource](IAsyncEnumerable`1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable`1.Enumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.MoveNextCore(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.AsyncIterator`1.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)
ClientConnectionId:68090395-2d00-4ce7-9f2b-0ed6813b9694
Error Number:208,State:1,Class:16
System.AggregateException: One or more errors occurred. (Invalid object name 'AspNetUsers'.) ---> System.Data.SqlClient.SqlException: Invalid object name 'AspNetUsers'.
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__122_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.FirstOrDefault_[TSource](IAsyncEnumerable`1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable`1.Enumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.MoveNextCore(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.AsyncIterator`1.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult](QueryContext queryContext, Func`2 compiledQuery, IDiagnosticsLogger`1 logger, Type contextType)
at Microsoft.AspNetCore.Identity.UserManager`1.FindByEmailAsync(String email)
at BigProject.Data.Seeder.SeedAsync() in C:\Users\prywatny\Desktop\ProjektodZera\BigProject\BigProject\Data\Seeder.cs:line 32
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at BigProject.Program.SeedDb(IWebHost host) in C:\Users\prywatny\Desktop\ProjektodZera\BigProject\BigProject\Program.cs:line 32
at BigProject.Program.Main(String[] args) in C:\Users\prywatny\Desktop\ProjektodZera\BigProject\BigProject\Program.cs:line 22
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred in the database while iterating the results of a query for context type 'BigProject.Data.Context'.
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'AspNetUsers'.
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__122_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.FirstOrDefault_[TSource](IAsyncEnumerable`1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable`1.Enumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.MoveNextCore(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.AsyncIterator`1.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult](QueryContext queryContext, Func`2 compiledQuery, IDiagnosticsLogger`1 logger, Type contextType)
ClientConnectionId:68090395-2d00-4ce7-9f2b-0ed6813b9694
Error Number:208,State:1,Class:16
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'AspNetUsers'.
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__122_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.FirstOrDefault_[TSource](IAsyncEnumerable`1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable`1.Enumerator.MoveNext(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.MoveNextCore(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.AsyncIterator`1.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult](QueryContext queryContext, Func`2 compiledQuery, IDiagnosticsLogger`1 logger, Type contextType)
ClientConnectionId:68090395-2d00-4ce7-9f2b-0ed6813b9694
Error Number:208,State:1,Class:16
C:\Users\prywatny\Desktop\ProjektodZera\BigProject\BigProject>
Thanks for any help.
The error is quite clear at the top of the stack trace you posted, although these big error messages can be hard to read sometimes:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (133ms) [Parameters=[#__normalizedEmail_0='?' (Size = 256)], CommandType='Text', CommandTimeout='30']
SELECT TOP(1) [u].[Id], [u].[AccessFailedCount], [u].[ConcurrencyStamp], [u].[Email], [u].[EmailConfirmed], [u].[FirstName], [u].[LastName], [u].[LockoutEnabled], [u].[LockoutEnd], [u].[NormalizedEmail], [u].[NormalizedUserName], [u].[PasswordHash], [u].[PhoneNumber], [u].[PhoneNumberConfirmed], [u].[SecurityStamp], [u].[TwoFactorEnabled], [u].[UserName]
FROM [AspNetUsers] AS [u]
WHERE [u].[NormalizedEmail] = #__normalizedEmail_0
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'AspNetUsers'.
So the system is trying to run the query:
SELECT TOP(1) [u].[Id], [u].[AccessFailedCount], [u].[ConcurrencyStamp], [u].[Email], [u].[EmailConfirmed], [u].[FirstName], [u].[LastName], [u].[LockoutEnabled], [u].[LockoutEnd], [u].[NormalizedEmail], [u].[NormalizedUserName], [u].[PasswordHash], [u].[PhoneNumber], [u].[PhoneNumberConfirmed], [u].[SecurityStamp], [u].[TwoFactorEnabled], [u].[UserName]
FROM [AspNetUsers] AS [u]
WHERE [u].[NormalizedEmail] = #__normalizedEmail_0
And is getting the error:
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'AspNetUsers'.
You should check that the table exists and that the user account you are using has access to the table. You could even try running the query yourself from SQL Management Studio to see what happens

LUIS recognizer method stopped working (Code hasn't been changed)

I didn't change any of my code and the method throws an LUIS.Runtime.Models.APIErrorException
_services.LuisServices[LuisConfiguration].RecognizeAsync(turnContext, cancellationToken);
I tried to use a different LUIS model and an old version of my bot that definately worked. It seems like something was changed in the BotBuilder and I can't figure out what. This is the stacktrace:
Exception caught : Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.Models.APIErrorException: Operation returned an invalid status code 'Forbidden'
at Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.Prediction.ResolveWithHttpMessagesAsync(String appId, String query,
Nullable`1 timezoneOffset, Nullable`1 verbose,
Nullable`1 staging, Nullable`1 spellCheck, String bingSpellCheckSubscriptionKey,
Nullable`1 log, Dictionary`2 customHeaders, CancellationToken cancellationToken)
at Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.PredictionExtensions.ResolveAsync(IPrediction operations, String appId, String query,
Nullable`1 timezoneOffset, Nullable`1 verbose,
Nullable`1 staging,
Nullable`1 spellCheck,
String bingSpellCheckSubscriptionKey, Nullable`1 log, CancellationToken cancellationToken)
at Microsoft.Bot.Builder.AI.Luis.LuisRecognizer
.RecognizeInternalAsync(ITurnContext turnContext, CancellationToken cancellationToken) in D:\a\1\s\libraries\Microsoft.Bot.Builder.AI.LUIS
\LuisRecognizer.cs:line 421
at Microsoft.Bot.Builder.AI.Luis.LuisRecognizer
.RecognizeAsync(ITurnContext turnContext, CancellationToken cancellationToken) in D:\a\1\s\libraries\Microsoft.Bot.Builder.AI.LUIS
\LuisRecognizer.cs:line 112
at NLPMortBot.BasicBot.OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken) in nlpmortbot\NLPMortBot\BasicBot.cs:line 121
at Microsoft.Bot.Builder.MiddlewareSet.ReceiveActivityWithStatusAsync(ITurnContext turnContext, BotCallbackHandler callback,
CancellationToken cancellationToken) in D:\a\1\s\libraries\Microsoft.Bot.Builder\MiddlewareSet.cs:line 55
at Microsoft.Bot.Builder.BotAdapter.RunPipelineAsync(ITurnContext turnContext, BotCallbackHandler callback,
CancellationToken cancellationToken) in D:\a\1\s\libraries\Microsoft.Bot.Builder\BotAdapter.cs:line 167
Thanks in advance guys !
This can happen if you are using the Starter Key instead of an actual Subscription Key from an 'endpoint runtime resource in Azure'. More information can be found here: https://learn.microsoft.com/en-us/azure/cognitive-services/luis/luis-how-to-azure-subscription
After creating the LUIS Azure Resource Key, it can be assigned within the LUIS Portal:
More information can be found here: https://learn.microsoft.com/en-us/azure/cognitive-services/luis/get-started-portal-deploy-app#assign-the-resource-key-to-the-luis-app-in-the-luis-portal

Namespace 'System' not to be found

I know this question have been asked before but no solution worked for me.
I'm working on a Win 10 app. I'm actually trying to open microsoft's samples :
github.com/Microsoft/Windows-universal-samples
I tried to run VS as administrator, to uninstall/reinstall, creting a web.config file...
My error in text :
System.TypeLoadException
Type Windows Runtime 'Windows.UI.Xaml.Hosting.IXamlUIPresenterHost' introuvable.
at Microsoft.VisualStudio.DesignTools.WindowsXamlDesigner.WindowsStoreXamlPlatform.SetThemeFolder(String path)
at Microsoft.VisualStudio.DesignTools.WindowsXamlDesigner.WindowsStoreXamlPlatformCreator.CreatePlatformInternal(IPlatformReferenceAssemblyResolver referenceAssemblyResolver)
at Microsoft.VisualStudio.DesignTools.Platform.PlatformCreatorBase.CreatePlatform(IPlatformReferenceAssemblyResolver referenceAssemblyResolver)
at Microsoft.VisualStudio.DesignTools.Designer.Project.ProjectContextManager.GetProjectContext(IHostProject project, IPlatform platform, Boolean create)
at Microsoft.VisualStudio.DesignTools.Designer.Project.ProjectContextManager.GetSourceItemContext(IHostSourceItem sourceItem)
at Microsoft.VisualStudio.DesignTools.Designer.DesignerService.CreateDesigner(IHostSourceItem item, IHostTextEditor editor, CancellationToken cancelToken)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.RemoteDesignerService.<>c__DisplayClass12_0.b__0(CancellationToken cancelToken)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.RemoteDesignerService.<>c__DisplayClass6_0`1.b__0()
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
System.TypeLoadException
Type Windows Runtime 'Windows.UI.Xaml.Hosting.IXamlUIPresenterHost' introuvable.
Server stack trace:
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.STAMarshaler.WaitForCompletion(NestedCallContext nestedCallContext, BlockingCall call, WaitHandle timeoutSignal)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.STAMarshaler.MarshalInSynchronous(Action action, Int32 targetApartmentId, CancellationToken cancelToken, CallModality callModality, String methodName, String filePath, Int32 lineNumber)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.STAMarshaler.MarshalIn(Action action, Int32 targetApartmentId, CancellationToken cancelToken, CallSynchronizationMode syncMode, CallModality callModality, String methodName, String filePath, Int32 lineNumber)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.ThreadMarshaler.MarshalIn(IRemoteObject targetObject, Action action, CancellationToken cancelToken, CallSynchronizationMode syncMode, CallModality callModality, ApartmentState apartmentState, String memberName, String filePath, Int32 lineNumber)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.RemoteDesignerService.MarshalInWithCancellation[TResult](IRemoteCancellationToken remoteToken, Func`2 func, ApartmentState apartmentState)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.RemoteDesignerService.Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.IRemoteDesignerService.CreateDesigner(IRemoteHostProject remoteProject, IRemoteHostSourceItem remoteItem, IRemoteHostTextEditor remoteEditor, IRemoteCancellationToken remoteToken)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [0]:
à System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
à System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.IRemoteDesignerService.CreateDesigner(IRemoteHostProject remoteProject, IRemoteHostSourceItem remoteItem, IRemoteHostTextEditor remoteEditor, IRemoteCancellationToken cancelToken)
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.LocalDesignerService.CreateDesignerImpl(IRemoteDesignerService ds, IHostSourceItem item, IHostTextEditor editor, RemoteCancellationToken remoteCancelToken)
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.LocalDesignerService.<>c__DisplayClass14_0.b__0(IRemoteDesignerService ds, RemoteCancellationToken remoteToken)
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.LocalDesignerService.<>c__DisplayClass5_01.<MarshalOutWithCancellation>b__0(IRemoteDesignerService ds)
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.ThreadMarshaler.<>c__DisplayClass28_01.b__0()
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
System.TypeLoadException
Type Windows Runtime 'Windows.UI.Xaml.Hosting.IXamlUIPresenterHost' introuvable.
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.STAMarshaler.WaitForCompletion(NestedCallContext nestedCallContext, BlockingCall call, WaitHandle timeoutSignal)
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.STAMarshaler.MarshalOutSynchronous(Action action, Int32 targetApartmentId, WaitHandle aborted, WaitHandle timeoutSignal, CancellationToken cancelToken, String methodName, String filePath, Int32 lineNumber)
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.STAMarshaler.MarshalOut(Action action, Int32 targetApartmentId, WaitHandle aborted, CancellationToken cancelToken, CallSynchronizationMode syncMode, WaitHandle timeoutSignal, String methodName, String filePath, Int32 lineNumber)
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.ThreadMarshaler.MarshalOut[TValue](RemoteHandle1 targetObject, Action action, CancellationToken cancelToken, CallSynchronizationMode syncMode, ApartmentState apartmentState, String methodName, String filePath, Int32 lineNumber)
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.ThreadMarshaler.MarshalOut[TValue](RemoteHandle1 targetObject, Action1 action, CancellationToken cancelToken, CallSynchronizationMode syncMode, ApartmentState apartmentState, String methodName, String filePath, Int32 lineNumber)
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.LocalDesignerService.MarshalOutWithCancellation[TResult](CancellationToken cancelToken, Func3 func, ApartmentState apartmentState)
à Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Remoting.LocalDesignerService.Microsoft.VisualStudio.DesignTools.DesignerContract.IDesignerService.CreateDesigner(IHostSourceItem item, IHostTextEditor editor, CancellationToken cancelToken)
à Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.IsolatedDesignerView.CreateDesignerViewInfo(CancellationToken cancelToken)

Categories

Resources