Issues with migration EF Core + ASP Identity + IdentityServer4 - asp.net-core

Trying to implement the IdentityServer 4 with Asp Core Identity and EF Core.
This tutorial to be precise (done every other before it as required): AspIdentity with EF Core
Everything is great until i have to run the migrations, which throws error:
An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Invalid object name 'Clients'.
No DbContext named 'ConfigurationDbContext' was found.
The full stack trace below:
C:\CodeRepos\horrorServerCORE\IdentityProvider>dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using 'C:\Users\horror\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
info: Microsoft.EntityFrameworkCore.Infrastructure[100403]
Entity Framework Core 2.0.0-rtm-26452 initialized 'PersistedGrantDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: MigrationsAssembly=IdentityProvider
info: Microsoft.EntityFrameworkCore.Database.Command[200101]
Executed DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'__EFMigrationsHistory');
info: Microsoft.EntityFrameworkCore.Database.Command[200101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'__EFMigrationsHistory');
info: Microsoft.EntityFrameworkCore.Database.Command[200101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [MigrationId], [ProductVersion]
FROM [__EFMigrationsHistory]
ORDER BY [MigrationId];
info: Microsoft.EntityFrameworkCore.Migrations[200405]
No migrations were applied. The database is already up to date.
info: Microsoft.EntityFrameworkCore.Infrastructure[100403]
Entity Framework Core 2.0.0-rtm-26452 initialized 'ConfigurationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: MigrationsAssembly=IdentityProvider
info: Microsoft.EntityFrameworkCore.Database.Command[200101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'__EFMigrationsHistory');
info: Microsoft.EntityFrameworkCore.Database.Command[200101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT OBJECT_ID(N'__EFMigrationsHistory');
info: Microsoft.EntityFrameworkCore.Database.Command[200101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [MigrationId], [ProductVersion]
FROM [__EFMigrationsHistory]
ORDER BY [MigrationId];
info: Microsoft.EntityFrameworkCore.Migrations[200405]
No migrations were applied. The database is already up to date.
fail: Microsoft.EntityFrameworkCore.Database.Command[200102]
Failed executing DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT CASE
WHEN EXISTS (
SELECT 1
FROM [Clients] AS [c])
THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
END
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'Clients'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
ClientConnectionId:073e455e-7472-459d-9f9b-36504b8ef1ae
Error Number:208,State:1,Class:16
fail: Microsoft.EntityFrameworkCore.Query[100100]
An exception occurred in the database while iterating the results of a query for context type 'IdentityServer4.EntityFramework.DbContexts.ConfigurationDbContext'.
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'Clients'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(Boolean buffer)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.GetResult[TResult](IEnumerable`1 valueBuffers, Boolean throwOnNullResult)
at lambda_method(Closure , QueryContext )
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass17_0`1.<CompileQueryCore>b__0(QueryContext qc)
ClientConnectionId:073e455e-7472-459d-9f9b-36504b8ef1ae
Error Number:208,State:1,Class:16
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'Clients'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(Boolean buffer)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.GetResult[TResult](IEnumerable`1 valueBuffers, Boolean throwOnNullResult)
at lambda_method(Closure , QueryContext )
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass17_0`1.<CompileQueryCore>b__0(QueryContext qc)
ClientConnectionId:073e455e-7472-459d-9f9b-36504b8ef1ae
Error Number:208,State:1,Class:16
An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Invalid object name 'Clients'.
No DbContext named 'ConfigurationDbContext' was found.
My Startup.cs class:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
var connectionString = Configuration.GetConnectionString("DefaultConnection");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
// configure identity server
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddAspNetIdentity<ApplicationUser>()
// this adds the config data from DB (clients, resources)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
options.TokenCleanupInterval = 30;
});
services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
InitializeDatabase(app);
app.UseCors("default");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentityServer();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
private void InitializeDatabase(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
context.Database.Migrate();
if (!context.Clients.Any())
{
foreach (var client in Config.GetClients())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
if (!context.IdentityResources.Any())
{
foreach (var resource in Config.GetIdentityResources())
{
context.IdentityResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
if (!context.ApiResources.Any())
{
foreach (var resource in Config.GetApiResources())
{
context.ApiResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
}
}
}
NOTE: I started brand new project in ASP Core 2 framework so no migration from 1.x to 2.0 was needed.
What am i doing wrong?

To run an Entity Framework migration you need to disable the InitialiseDatabase call.
Once the migration has been created you can enable it again.

I know it's not your answer but if anyone else runs into this I found another cause. I was adding the ConfigurationDbContext to the DI container before adding it to IdentityServer and that caused the migration to not get added via IdentityServer.
Startup:
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
var optionsContextBuilder = new Action<DbContextOptionsBuilder>(options => options.UseSqlServer(authConnectionString, sql => sql.MigrationsAssembly(migrationsAssembly)));
// This caused my migration to not get run
services.AddDbContext<ConfigurationDbContext>(options => options.UseSqlServer(authConnectionString));
services.AddSingleton(sp => new ConfigurationStoreOptions { ConfigureDbContext = optionsContextBuilder });
// The above two lines needed to be moved below these lines
identityServerBuilder
.AddSigningCredential(certificate)
.AddConfigurationStore(options => options.ConfigureDbContext = optionsContextBuilder)
.AddOperationalStore(options => options.ConfigureDbContext = optionsContextBuilder)
Hope this helps someone else!

Related

Error uploading a document to SQL Server in .Net Core 3.1 Web API

I have a SQL Server stored procedure that is used for uploading a document and returns an ID upon success.
I am storing the parameter file_data into a byte[] type in the Customer_Document_ADD class.
public byte[] file_data { get; set; }
The following is my repository code.
public async Task<int> InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED)
{
await using(SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
// define SqlParameters for the other two params to be passed
var company_idParam = new SqlParameter("#company_id", customer_Document_ADDED.company_id);
var customer_idParam = new SqlParameter("#customer_id", customer_Document_ADDED.customer_id);
var customer_site_idParam = new SqlParameter("#customer_site_id", customer_Document_ADDED.customer_site_id);
var customer_system_idParam = new SqlParameter("#customer_system_id", customer_Document_ADDED.customer_system_id);
var job_idParam = new SqlParameter("#job_id", customer_Document_ADDED.job_id);
var security_levelParam = new SqlParameter("#security_level", customer_Document_ADDED.security_level);
var file_nameParam = new SqlParameter("#file_name", customer_Document_ADDED.file_name);
var file_sizeParam = new SqlParameter("#file_size", customer_Document_ADDED.file_size);
var upload_dateParam = new SqlParameter("#upload_date", customer_Document_ADDED.upload_date);
var document_extParam = new SqlParameter("#document_ext", customer_Document_ADDED.document_ext);
var user_codeParam = new SqlParameter("#user_code", customer_Document_ADDED.user_code);
var user_descriptionParam = new SqlParameter("#user_description", customer_Document_ADDED.user_description);
var reference1Param = new SqlParameter("#reference1", customer_Document_ADDED.reference1);
var reference2Param = new SqlParameter("#reference2", customer_Document_ADDED.reference2);
var reference3Param = new SqlParameter("#reference3", customer_Document_ADDED.reference3);
var reference4Param = new SqlParameter("#reference4", customer_Document_ADDED.reference4);
var file_dataParam = new SqlParameter("#file_data", customer_Document_ADDED.file_data);
//if (file_dataParam.Value == null)
//{
// file_dataParam.Value = "";
//}
file_dataParam.SqlDbType = SqlDbType.Image;
// define the output parameter that needs to be retained
// for the Id created when the Stored Procedure executes
// the INSERT command
var document_idParam = new SqlParameter("#document_id", SqlDbType.Int);
// the direction defines what kind of parameter we're passing
// it can be one of:
// Input
// Output
// InputOutput -- which does pass a value to Stored Procedure and retains a new state
document_idParam.Direction = ParameterDirection.Output;
// we can also use context.Database.ExecuteSqlCommand() or awaitable ExecuteSqlCommandAsync()
// which also produces the same result - but the method is now marked obselete
// so we use ExecuteSqlRawAsync() instead
// we're using the awaitable version since GetOrCreateUserAsync() method is marked async
await context.Database.ExecuteSqlRawAsync(
"EXECUTE [dbo].[Customer_Document_ADD_incentive] #company_id, #customer_id, #customer_site_id, #customer_system_id, #job_id, #security_level, #file_name, #file_size, #upload_date, #document_ext, #user_code, #user_description, #reference1, #reference2, #reference3, #reference4, #file_data, #document_id out",
company_idParam,
customer_idParam,
customer_site_idParam,
customer_system_idParam,
job_idParam,
security_levelParam,
file_nameParam,
file_sizeParam,
upload_dateParam,
document_extParam,
user_codeParam,
user_descriptionParam,
reference1Param,
reference2Param,
reference3Param,
reference4Param,
file_dataParam,
document_idParam);
// the userIdParam which represents the Output param
// now holds the Id of the new user and is an Object type
// so we convert it to an Integer and send
return Convert.ToInt32(document_idParam.Value);
}
}
I'm getting the following error in Postman.
Microsoft.Data.SqlClient.SqlException (0x80131904): The parameterized query '(#company_id int,#customer_id int,#customer_site_id int,#custome' expects the parameter '#file_data', which was not supplied.
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.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at Microsoft.Data.SqlClient.SqlCommand.CompleteAsyncExecuteReader(Boolean isInternal, Boolean forDescribeParameterEncryption)
at Microsoft.Data.SqlClient.SqlCommand.InternalEndExecuteNonQuery(IAsyncResult asyncResult, Boolean isInternal, String endMethod)
at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryInternal(IAsyncResult asyncResult)
at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlRawAsync(DatabaseFacade databaseFacade, String sql, IEnumerable`1 parameters, CancellationToken cancellationToken)
at WebAPI.Repository.Customer_Document_ADDRepository.InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Repository\Customer_Document_ADDRepository.cs:line 73
at WebAPI.Repository.Customer_Document_ADDRepository.InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Repository\Customer_Document_ADDRepository.cs:line 97
at WebAPI.Controllers.Customer_Document_ADDController.InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Controllers\Customer_Document_ADDController.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__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
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.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
ClientConnectionId:e8f735f0-1ab5-4d53-9ead-01df3ee63c2e
Error Number:8178,State:1,Class:16
All other values are captured except the file. I am getting a null value in the debugger. Why am I unable to upload a file into the database? Thanks in advance.
Firstly,default model binding system cannot bind file to byte[] properties.If you want to bind file to btye[],you can use ByteArrayModelBinder,here is an official link.
Also,if you don't mind to change the type of file_data,you can use
public IFormFile file_data { get; set; }
and then you can convert it to byte[] type with MemoryStream.Here is an official link about upload files in .net core.

Intercept Error Record Cancellation with Forrenkey Bond

I'm creating a web application for the parish in angular.
It is a CRUD web application in which I use SQL Server.
I have the product-list.component page where I created the OnDelete method to be able to delete the single product.
The method is correct, but I have a problem that in the table there are relations to the "CommandRighe" table that inhibit deletion.
I modified the OnDelete method with try catch to be able to intercept the error code and send an error message to the user.
It does not work and I would like to know how to handle the problem in order to send the user an error message telling him that the record cannot be deleted.
How can I do ?
thank you
Moreno
System.Data.Entity.Infrastructure.DbUpdateException non è stata gestita dal codice utente
HResult=-2146233087
Message=Errore durante l'aggiornamento delle voci. Per ulteriori dettagli, vedere l'eccezione interna.
Source=EntityFramework
StackTrace:
in System.Data.Entity.Internal.InternalContext.SaveChanges()
in System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
in System.Data.Entity.DbContext.SaveChanges()
in WebApiSif.Controllers.PRODOTTIController.DeletePRODOTTI(Int32 id) in I:\Angular Project\SifWork\WebApiSif\WebApiSif\Controllers\PRODOTTIController.cs:riga 162
in lambda_method(Closure , Object , Object[] )
in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)
in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
InnerException:
HResult=-2146233087
Message=Errore durante l'aggiornamento delle voci. Per ulteriori dettagli, vedere l'eccezione interna.
Source=EntityFramework
StackTrace:
in System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
in System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
in System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
in System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
in System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
in System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
in System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
in System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
in System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
in System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
in System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
in System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException:
Class=16
ErrorCode=-2146232060
HResult=-2146232060
LineNumber=1
Message=L'istruzione DELETE è in conflitto con il vincolo REFERENCE "FK_CommandaRighe_PRODOTTI". Il conflitto si è verificato nella tabella "dbo.CommandaRighe", column 'NProdotto' del database "SifDB".
L'istruzione è stata interrotta.
Number=547
Procedure=""
Server=DESKTOP-P3TEF6K\SQLEXPRESS
Source=.Net SqlClient Data Provider
State=0
StackTrace:
in System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
in System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
in System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
in System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
in System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
in System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
in System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
in System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
in System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
in System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
in System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
in System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
in System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
in System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
in System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
InnerException:
Message = The DELETE statement conflicts with the REFERENCE constraint "FK_CommandaRighe_PRODOTTI". The conflict occurred in the "dbo.CommandaRighe" table, column 'NProduct' of the "SifDB" database.
The instruction has been interrupted.
onDelete(id: number) {
if (confirm('Confermi la cancellazione del Record ?')) {
try {
this.service.deleteProdotti(id).then(res => { // this.service.deleteProdotti(id).subscribe(res => {
this.service.refreshList();
this.toastr.warning('Cancellazione eseguita con successo', Header_Msg);
});
} catch (error) {
console.error('errore in cancellazione: ' + error);
}
}
}
-----------------------------------------
the overall class is as follows
import {Component, OnInit, SystemJsNgModuleLoader} from '# angular / core';
import {Products} from 'src / app / model / prodotti.model';
import {ProductsListService} from 'src / app / features / products / components / products-list / products-list.service';
import {ToastrService} from 'ngx-toastr';
let Header_Msg = "Product Manager";
#Component ({
selector: 'app-products-list',
templateUrl: './products-list.component.html',
styleUrls: ['./products-list.component.css']
})
export class ProductsListComponent implements OnInit {
constructor (private service: ProductsListService, private toastr: ToastrService) {
}
ngOnInit () {
this.service.refreshList ();
}
populateForm (emp: Products) {
this.service.formData = Object.assign ({}, emp);
}
onDelete (id: number) {
if (confirm ('Confirm the deletion of the record?')) {
try {
this.service.deleteProducts (id) .then (res => {// this.service.deleteProdotti (id) .subscribe (res => {
this.service.refreshList ();
this.toastr.warning ('Successful deletion', Header_Msg);
});
} catch (error) {
console.error ('error in deletion:' + error);
}
}
}
}`enter code here`

Returning Error Message from Web API

I have a Web API controller method...
[HttpGet]
[Route("~/Api/Tag/GetTagTaskMappings")]
public IHttpActionResult GetTagTaskMappings()
{
try
{
var tagTaskMappings = _tagRepository.GetTagTaskMappings();
if (tagTaskMappings == null)
{
return NotFound();
}
return Ok(tagTaskMappings);
}
catch (Exception ex)
{
return InternalServerError(ex.InnerException);
}
}
I am using Postman to debug the method.
I am testing the Web API in 2 scenarios...
Running in Visual Studio (IIS Express)
Running on IIS Manager on a remote server
Using Postman I get the desired results from scenario 1 test...
{
"Message": "An error has occurred.",
"ExceptionMessage": "No Tag/Task Relationship found",
"ExceptionType": "System.Data.SqlClient.SqlException",
"StackTrace": " at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()\r\n at System.Data.SqlClient.SqlDataReader.get_MetaData()\r\n at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)\r\n 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)\r\n at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)\r\n at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)"
}
However, for scenario 2 test, I only get this back from Postman...
{
"Message": "An error has occurred."
}
Any idea why I am not getting the ExceptionMessage? Am I error handling correctly?
The only difference I see in Postman is scenario 1 has one extra header...
X-SourceFiles →=?UTF-8?B?XFxTVlB

ASPX Write to SQL Datatypes

I want to write to my SQL databse, but getting this specific error:
System.Data.SqlClient.SqlException (0x80131904): Must declare the
scalar variable "#Aantalpaginas". at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) at
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds, Boolean describeParameterEncryptionRequest) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1
completion, String methodName, Boolean sendToPipe, Int32 timeout,
Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
project.NEWANDWRITE.btnOpslaan_Click(Object sender, EventArgs e) in
Error Number:137,State:2,Class:15
This are my datatypes in SQL:
http://imgur.com/qj2oSsb
I think i need to convert the text in the txtPaginas.text to an int right?
if (Page.IsValid)
{
string connString = WebConfigurationManager.ConnectionStrings["csBoeken"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connString);
string sqlWegschrijven = "INSERT INTO TabelBoeken (ISBN, Titel, Auteur, Uitgever, JaarUitgifte, Aantalpaginas, Aanschafprijs) VALUES (#ISBN, #Titel, #Auteur, #Uitgever, #JaarUitgifte, #Aantalpaginas, #Aanschafprijs)";
SqlCommand cmdSchrijfNaarDB = new SqlCommand(sqlWegschrijven, myConnection);
cmdSchrijfNaarDB.Parameters.AddWithValue("#Titel", txtTitel.Text);
cmdSchrijfNaarDB.Parameters.AddWithValue("#Auteur", txtAuteur.Text);
cmdSchrijfNaarDB.Parameters.AddWithValue("#ISBN", txtISBN.Text);
cmdSchrijfNaarDB.Parameters.AddWithValue("#Uitgever", txtUitgever.Text);
cmdSchrijfNaarDB.Parameters.AddWithValue("#JaarUitgifte", txtJaar.Text);
cmdSchrijfNaarDB.Parameters.AddWithValue("#Aantalpagina", txtPagina.Text);
cmdSchrijfNaarDB.Parameters.AddWithValue("#Aanschafprijs", txtPrijs.Text);
try
{
myConnection.Open();
cmdSchrijfNaarDB.ExecuteNonQuery();
}
catch (Exception error)
{
lblError.Text = error.ToString();
}
finally
{
myConnection.Close();
}
}
You have a spelling error on parameter #6
if (Page.IsValid)
{
string connString = WebConfigurationManager.ConnectionStrings["csBoeken"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connString);
string sqlWegschrijven = "INSERT INTO TabelBoeken (ISBN, Titel, Auteur, Uitgever, JaarUitgifte, Aantalpaginas, Aanschafprijs) VALUES (#ISBN, #Titel, #Auteur, #Uitgever, #JaarUitgifte, #Aantalpaginas, #Aanschafprijs)";
SqlCommand cmdSchrijfNaarDB = new SqlCommand(sqlWegschrijven, myConnection);
cmdSchrijfNaarDB.Parameters.AddWithValue("#Titel", txtTitel.Text);
cmdSchrijfNaarDB.Parameters.AddWithValue("#Auteur", txtAuteur.Text);
cmdSchrijfNaarDB.Parameters.AddWithValue("#ISBN", txtISBN.Text);
cmdSchrijfNaarDB.Parameters.AddWithValue("#Uitgever", txtUitgever.Text);
cmdSchrijfNaarDB.Parameters.AddWithValue("#JaarUitgifte", txtJaar.Text);
cmdSchrijfNaarDB.Parameters.AddWithValue("#Aantalpaginas", txtPagina.Text); // Correct spelling is #Aantalpaginas
cmdSchrijfNaarDB.Parameters.AddWithValue("#Aanschafprijs", txtPrijs.Text);
try
{
myConnection.Open();
cmdSchrijfNaarDB.ExecuteNonQuery();
}
catch (Exception error)
{
lblError.Text = error.ToString();
}
finally
{
myConnection.Close();
}
}

System.Data.SqlClient.SqlException (0x80131904): Invalid column name

I am getting this error while trying to execute the attached code. Please help. I am getting values as list array in controller method successfully but when I try to read data from sql database I am getting error.
Controller method:
[HttpPost]
public JsonResult searchdata(List<string> firstField, List<string> secondField, List<string> thirdField)
{
List<string> lt = new List<string>();
Console.WriteLine(firstField);
Console.WriteLine(secondField);
string dogCsv = string.Join(",", firstField.ToArray());
Console.WriteLine(dogCsv);
try
{
using (SqlConnection connection = new SqlConnection("data source=.; database=Srivatsava; integrated security=SSPI"))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandTimeout = 0;
command.CommandText = #"select accntname,BU,salesop,isdormant from fourth_page as fg
INNER JOIN linked as ld on ld.productid=fg.productid
INNER JOIN isdormant as it on it.productid=ld.productid
where fg.accountname in (" + dogCsv + ")";
//command.Parameters.AddWithValue("firstField", dogCsv);
using (SqlDataReader sdr = command.ExecuteReader())
{
while (sdr.Read())
{
lt.Add(sdr["accntname"].ToString());
}
}
}
connection.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine(lt);
return Json(firstField);
}
Execption:-
{System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'account2'.
Invalid column name 'account1'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader()
at MvcApplication32.Controllers.TodoListController.searchdata(List`1 firstField, List`1 secondField, List`1 thirdField) in c:\Users\ADMIN\Documents\Visual Studio 2012\Projects\MvcApplication32\MvcApplication32\Controllers\TodoListController.cs:line 597
ClientConnectionId:a0674fe4-e0d5-499f-be61-66e1b27768fa}
Since you are using inline SQL, every value within dogCSV string that's comma separated needs a single quote around it. For instance, if dogCSV has "account2,someotheraccount", this won't work it needs to be "'account2','someotheraccount'".
If you don't that definitely would be the issue.
EDIT: Build dogCSV like this:
string dogCsv = string.Join(",", firstField.Select(i => "'" + i + "'"));
The way it's built now will not put quotes around it.