AspNetCore.Identity using PostgreSQL: how to create structure? - postgresql

I have a ASP.NET Core web application with AspNetCore.Identity
Logins. It uses SQL Server for user authentication.
I need to use PostgreSQL database I have added some nuget packages (EF.* etc), changed the connection string and code
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
});
// options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql( Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews()
.AddNewtonsoftJson();
services.AddRazorPages();
}
But when I run it, it connects to the PostgreSQL database and tries to create the structure I receive the error, what is wrong? Why EF cannot create the structure? How to solve this problem?
Executing endpoint 'WebApplication1.Controllers.HomeController.Index (WebA
pplication1)'
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Index", controller = "Home", page = "", area
= ""}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IAct
ionResult Index() on controller WebApplication1.Controllers.HomeController (WebA
pplication1).
info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[1]
Executing ViewResult, running view Index.
info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[4]
Executed ViewResult - view Index executed in 302.6169ms.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action WebApplication1.Controllers.HomeController.Index (WebAppli
cation1) in 315.3645ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'WebApplication1.Controllers.HomeController.Index (WebAp
plication1)'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 451.9255ms 200 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET https://localhost:5001/Identity/Account/Logi
n
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint '/Account/Login'
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[3]
Route matched with {page = "/Account/Login", area = "Identity", action = "
", controller = ""}. Executing page /Account/Login
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[101]
Executing handler method Microsoft.AspNetCore.Identity.UI.V4.Pages.Account
.Internal.LoginModel.OnGetAsync - ModelState is Valid
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[11
]
AuthenticationScheme: Identity.External signed out.
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[102]
Executed handler method OnGetAsync, returned result .
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[103]
Executing an implicit handler method - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[104]
Executed an implicit handler method, returned result Microsoft.AspNetCore.
Mvc.RazorPages.PageResult.
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[4]
Executed page /Account/Login in 104.6291ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint '/Account/Login'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 157.5038ms 200 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 POST https://localhost:5001/Identity/Account/Log
in application/x-www-form-urlencoded 264
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint '/Account/Login'
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[3]
Route matched with {page = "/Account/Login", area = "Identity", action = "
", controller = ""}. Executing page /Account/Login
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[101]
Executing handler method Microsoft.AspNetCore.Identity.UI.V4.Pages.Account
.Internal.LoginModel.OnPostAsync - ModelState is Valid
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 3.1.0 initialized 'ApplicationDbContext' using provi
der 'Npgsql.EntityFrameworkCore.PostgreSQL' with options: None
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (182ms) [Parameters=[#__normalizedUserName_0='?
'], CommandType='Text', CommandTimeout='30']
SELECT a."Id", a."AccessFailedCount", a."ConcurrencyStamp", a."Email", a."
EmailConfirmed", a."LockoutEnabled", a."LockoutEnd", a."NormalizedEmail", a."Nor
malizedUserName", a."PasswordHash", a."PhoneNumber", a."PhoneNumberConfirmed", a
."SecurityStamp", a."TwoFactorEnabled", a."UserName"
FROM "AspNetUsers" AS a
WHERE a."NormalizedUserName" = #__normalizedUserName_0
LIMIT 1
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for cont
ext type 'WebApplication1.Data.ApplicationDbContext'.
Npgsql.PostgresException (0x80004005): 42P01: relation "AspNetUsers" does
not exist
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__Rea
dMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown -
--
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__Rea
dMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown -
--
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsumin
g)
at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Bo
olean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavi
or, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReade
rAsync(RelationalCommandParameterObject parameterObject, CancellationToken cance
llationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReade
rAsync(RelationalCommandParameterObject parameterObject, CancellationToken cance
llationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReade
rAsync(RelationalCommandParameterObject parameterObject, CancellationToken cance
llationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.As
yncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationTok
en cancellationToken)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecuti
onStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 v
erifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.As
yncEnumerator.MoveNextAsync()
Exception data:
Severity: ERROR
SqlState: 42P01
MessageText: relation "AspNetUsers" does not exist
Position: 294
File: parse_relation.c
Line: 1159
Routine: parserOpenTable
Npgsql.PostgresException (0x80004005): 42P01: relation "AspNetUsers" does not ex
ist
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessa
geLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessa
geLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)
at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean
async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, Ca
ncellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync
(RelationalCommandParameterObject parameterObject, CancellationToken cancellatio
nToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync
(RelationalCommandParameterObject parameterObject, CancellationToken cancellatio
nToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync
(RelationalCommandParameterObject parameterObject, CancellationToken cancellatio
nToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnu
merator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken can
cellationToken)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStra
tegy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifyS
ucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnu
merator.MoveNextAsync()
Exception data:
Severity: ERROR
SqlState: 42P01
MessageText: relation "AspNetUsers" does not exist
Position: 294
File: parse_relation.c
Line: 1159
Routine: parserOpenTable
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[4]
Executed page /Account/Login in 2362.999ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint '/Account/Login'
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (18ms) [Parameters=[], CommandType='Text', CommandTimeo
ut='30']
SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_name
space n ON n.oid=c.relnamespace WHERE c.relname='__EFMigrationsHistory');
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 3019.116ms 500 text/html; charset=utf-8

I had to go a bit further than changing the provider and connection string.
In my ApplicationDbContext class:
First, I had an issue with Postgresql wanting to force double-quotes to be added to unquoted identifiers and automatically folding them to lower-case.
PostgreSQL Docs.
My solution was to install the EFCore.NamingConventions package. Then override OnConfiguring as shown below.
Identity 3.0 is apparently expecting the "dbo" schema to be used. Consequently, that needs to be specified by setting the default schema ("public" in this example and that is also the default for Postgresql) by overriding OnModelCreating.
Finally, the database table names need to be lower-cased which is handled by the for loop in the OnModelCreating override.
In the ApplicationDbContext class:
public class ApplicationDbContext
: IdentityDbContext<IdentityUser<int>,IdentityRole<int>,int>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSnakeCaseNamingConvention();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// PostgreSQL uses the public schema by default - not dbo.
modelBuilder.HasDefaultSchema("public");
base.OnModelCreating(modelBuilder);
//Rename Identity tables to lowercase
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
var currentTableName = modelBuilder.Entity(entity.Name).Metadata.GetDefaultTableName();
modelBuilder.Entity(entity.Name).ToTable(currentTableName.ToLower());
}
}
public DbSet<Address> Address { get; set; }
}
After doing this I added a new migration:
add-migration modifyIdentityForPostgresql
Then updated the database schema:
update-database
Which results in the Identity tables being created.
Screen clip of newly created Identity tables in Postgresql

You should run database migration after change provider and connect string , so that the asp.net core identity tables will create in your PostgreSQL database :
Add-Migration InitialCreate
Update-database
Document : https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=vs

My answer is similar to the one that #Steven Tomlinson provided, but in his solution ExampleTableName becomes exampletablename<string>, which I didn't really like as my goal was snake_case.
Create a Helper.cs class
public class Helper
{
public static string ToUnderscoreCase(string str)
{
return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();
}
}
Install EFCore.NamingConventions
Edit ApplicationDbContext.cs:
public class ApplicationDbContext
: IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSnakeCaseNamingConvention(); // Not even sure if this is used? it
didn't seem to make any difference
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("public");
base.OnModelCreating(modelBuilder);
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
var currentTableName = modelBuilder.Entity(entity.Name).Metadata.GetDefaultTableName();
if (currentTableName.Contains("<"))
{
currentTableName = currentTableName.Split('<')[0];
}
modelBuilder.Entity(entity.Name).ToTable(Helper.ToUnderscoreCase(currentTableName));
}
}
}

Related

42P07: Error while updating Postgre Entity Framework Core database

I am trying to update the database using the EntityFramework migration, but this error crashes. I started looking at what they write on this issue, but everywhere the same thing, that do not use EnsureCreated in a startup and that's it. I don't have anything like that in a startup, here's the code in a startup:
services.AddDbContext<ApplicationDbContext>();
services.AddIdentity<IdentityUserModel, IdentityRole>(
options => options.SignIn.RequireConfirmedAccount = false
)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
Well, of course, adding authorization, adding providers, and so on. But as soon as I try to start the migration, the error falls below.
Who faced this problem or knows how to solve it, please tell me.
Thank you very much for your answers!
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "AspNetRoles" (
"Id" text NOT NULL,
"Name" character varying(256) NULL,
"NormalizedName" character varying(256) NULL,
"ConcurrencyStamp" text NULL,
CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id")
);
Failed executing DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "AspNetRoles" (
"Id" text NOT NULL,
"Name" character varying(256) NULL,
"NormalizedName" character varying(256) NULL,
"ConcurrencyStamp" text NULL,
CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id")
);
Npgsql.PostgresException (0x80004005): 42P07: отношение "AspNetRoles" уже существует
at Npgsql.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|194_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
at Npgsql.NpgsqlDataReader.NextResult()
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Exception data:
Severity: ОШИБКА
SqlState: 42P07
MessageText: отношение "AspNetRoles" уже существует
File: d:\pginstaller.auto\postgres.windows-x64\src\backend\catalog\heap.c
Line: 1094
Routine: heap_create_with_catalog
42P07: отношение "AspNetRoles" уже существует
This error seems to be a "duplicated relation" in Postgres. This means that you are probably trying to recreate a database table that already exists. You should double check your migrations - it's possible that for some reason it's trying to recreate a database that already exists.
Another reason would be some sort of unsync'ing between your migration and the database - maybe someone else created the table manually, for instance?

Data migration in code first error using postgresql as database in .net core 3.0

I am migrating data using code first approach and db is postgresql, on add-migration is working fine,but update-database is giving error as"42601: syntax error at or near "GENERATED", more details below:
> PM> add-migration migration
> Build started...
> Build succeeded.
> To undo this action, use Remove-Migration.
> PM> update-database
> Build started...
> Build succeeded.
> [15:18:48 Error] Microsoft.EntityFrameworkCore.Database.Command
> Failed executing DbCommand (298ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
> CREATE TABLE "Customers" (
> "CustomerId" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
> "CustomerName" text NULL,
> CONSTRAINT "PK_Customers" PRIMARY KEY ("CustomerId")
> );
>
> Npgsql.PostgresException (0x80004005): 42601: syntax error at or near "GENERATED"
> at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
> at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
> --- End of stack trace from previous location where exception was thrown ---
> at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)
> at Npgsql.NpgsqlDataReader.NextResult()
> at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
> at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
> at Npgsql.NpgsqlCommand.ExecuteNonQuery()
> at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject
> parameterObject)
> at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection
> connection, IReadOnlyDictionary`2 parameterValues)
> at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1
> migrationCommands, IRelationalConnection connection)
> at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String
> targetMigration)
> at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String
> targetMigration, String contextType)
> at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String
> targetMigration, String contextType)
> at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
> at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action
> action)
> Exception data:
> Severity: ERROR
> SqlState: 42601
> MessageText: syntax error at or near "GENERATED"
> Position: 63
> File: src\backend\parser\scan.l
> Line: 1067
> Routine: scanner_yyerror
> 42601: syntax error at or near "GENERATED"
(As this is code first approach so, below are the model)
Model:
public class Customer1
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CustomerId { get; set; }
public string CustomerName { get; set; }
}
**Update: Got a solution:
in migrationbuilder(created after add-migration command),i simply changed**
NpgsqlValueGenerationStrategy.IdentityByDefaultColumn
to
NpgsqlValueGenerationStrategy.serialcolumn
**and saved it ,and then run the command update-database ,and it worked**
You seem to be activating the IDENTITY columns feature, which was only introduced in PostgreSQL 10.(while you are 9.4.20)
I suggest that you could upgrade to a newer version of PostgreSQL.
Refer to https://dba.stackexchange.com/questions/198777/how-to-add-a-postgresql-10-identity-column-to-an-existing-table
Seriously! I doubt it's Postgres 3.x anything (released in '91). That may be your .net version. Please run this query: select version();
Your table definition uses "GENERATED BY DEFAULT AS IDENTITY". This initially appeared in version 10. If your version less then change that definition to:
create table Customers (
CustomerId serial
CustomerName text null,
constraint pk_customers primary key (CustomerId)
);
Note: I've removed the double quotes (") and would suggest you do the same. They just are not worth the trouble they cause.

EF Core Include method not working

I recently updated to asp.net core 2.0. Since upgrading all my Linq queries using Include Method are failing, it is not translated properly to SQL.
For instance this:
var entities = helpTopicRepository.Entities.Include(x => x.HelpArticles).FirstOrDefault(t => topicIds.Any(a => a == t.Id));
is translated to:
SELECT x.HelpArticles.ART_ID,
x.HelpArticles.AVAILABLE,
x.HelpArticles.CONTENT,
x.HelpArticles.DISPLAYORDER,
x.HelpArticles.HELPFULNO,
x.HelpArticles.HELPFULYES,
x.HelpArticles.KEYWORDS,
x.HelpArticles.TITLE,
x.HelpArticles.TOPICID
FROM HELPARTICLE x.HelpArticles
which is results in the following error:
Devart.Data.Oracle.OracleException (0x80004005): ORA-00933: SQL
command not properly ended at Devart.Data.Oracle.ay.b() at
Devart.Data.Oracle.am.f() at Devart.Data.Oracle.am.e() at
Devart.Data.Oracle.c5.a(am A_0, Int32 A_1) at
Devart.Data.Oracle.c5.a(Int32 A_0, bg A_1) at
Devart.Data.Oracle.OracleCommand.InternalExecute(CommandBehavior
behavior, IDisposable disposable, Int32 startRecord, Int32 maxRecords,
Boolean nonQuery) at
Devart.Common.DbCommandBase.ExecuteDbDataReader(CommandBehavior
behavior, Boolean nonQuery) at
Devart.Data.Oracle.Entity.ai.a(CommandBehavior A_0) at
Devart.Common.Entity.cj.d(CommandBehavior A_0) at
Devart.Data.Oracle.Entity.ai.b(CommandBehavior A_0) at
System.Data.Common.DbCommand.ExecuteReader() at
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection
connection, DbCommandMethod executeMethod, IReadOnlyDictionary2
parameterValues) at
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection
connection, IReadOnlyDictionary2 parameterValues) at
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.BufferlessMoveNext(Boolean
buffer) at
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()
at
Microsoft.EntityFrameworkCore.Query.Internal.QueryBuffer.IncludeCollection(Int32
includeId, INavigation navigation, INavigation inverseNavigation,
IEntityType targetEntityType, IClrCollectionAccessor
clrCollectionAccessor, IClrPropertySetter inverseClrPropertySetter,
Boolean tracking, Object entity, Func1 relatedEntitiesFactory) at
lambda_method(Closure , QueryContext , Client , Object[] ) at
Microsoft.EntityFrameworkCore.Query.Internal.IncludeCompiler._Include[TEntity](QueryContext
queryContext, TEntity entity, Object[] included, Action3 fixup) at
lambda_method(Closure , Client ) at
System.Linq.Enumerable.SelectEnumerableIterator2.MoveNext() at
System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source)
at lambda_method(Closure , QueryContext ) at
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass17_0`1.b__0(QueryContext
qc) ORA-00933: SQL command not properly ended
I'm using Devart dotconnect to connect to Oracle database.
Is due to your statement:
var entities = helpTopicRepository.Entities.Include(x => x.HelpArticles).FirstOrDefault(t => topicIds.Any(a => a == t.Id));
Assuming that topicIds is a list, here is a fix:
var entities = helpTopicRepository.Entities
.Include(x => x.HelpArticles)
.Where(t => topicIds.Contains(t.Id))
.FirstOrDefault();
The bug with using multiple .Include() in EF Core 2 is fixed. Look forward to the next public build of dotConnect for Oracle.

Asp.net core TempData give 500 error when adding list and redirect to another view

I am try to build alerts list and added them to TempData. But it work if I did not do redirect. When I do redirect it give me 500 error. I set break point in view as well but it did not hit when did redirect other wise it hit correctly.
ActionMethod
public IActionResult Create(CategoryCreateVM input)
{
if (ModelState.IsValid)
{
var category = mapper.Map<Categories>(input);
categoryBL.Add(category);
List<Alert> alert = new List<Alert>();
alert.Add(new Alert("alert-success", "success message"));
alert.Add(new Alert("alert-danger", "danger message"));
TempData["Alert"] = alert;
return RedirectToAction("Index");
}
return View(input);
}
How I access in view.
#{
var alerts = TempData["Alert"] as List<Alert>;
}
#if (alerts != null && alerts.Count > 0)
{
<div class="">
#foreach (var alert in alerts)
{
<div class="alert #alert.AlertClass alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#alert.Message
</div>
}
</div>
}
Stack Trace.
Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNetCore.Mvc.ViewFeatures.dll
Exception thrown: 'System.InvalidOperationException' in mscorlib.dll
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Information: Executed action MvcSandbox.Controllers.HomeController.Index (MvcSandbox) in 46.4619ms
Exception thrown: 'System.InvalidOperationException' in mscorlib.dll
Exception thrown: 'System.InvalidOperationException' in mscorlib.dll
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: Error: An unhandled exception has occurred while executing the request
System.InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer' cannot serialize an object of type 'MvcSandbox.Controllers.Alert'.
at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer.EnsureObjectCanBeSerialized(Object item) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\Internal\TempDataSerializer.cs:line 207
at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer.Serialize(IDictionary`2 values) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\Internal\TempDataSerializer.cs:line 142
at Microsoft.AspNetCore.Mvc.ViewFeatures.SessionStateTempDataProvider.SaveTempData(HttpContext context, IDictionary`2 values) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\ViewFeatures\SessionStateTempDataProvider.cs:line 62
at Microsoft.AspNetCore.Mvc.ViewFeatures.TempDataDictionary.Save() in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\ViewFeatures\TempDataDictionary.cs:line 166
at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.SaveTempDataFilter.SaveTempData(IActionResult result, ITempDataDictionaryFactory factory, HttpContext httpContext) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\Internal\SaveTempDataFilter.cs:line 91
at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.SaveTempDataFilter.OnResultExecuted(ResultExecutedContext context) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\Internal\SaveTempDataFilter.cs:line 80
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.Core\Internal\ControllerActionInvoker.cs:line 1023
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext() in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.Core\Internal\ControllerActionInvoker.cs:line 1105
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.Core\Internal\ControllerActionInvoker.cs:line 1377
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.Core\Internal\ControllerActionInvoker.cs:line 493
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext() in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.Core\Internal\ControllerActionInvoker.cs:line 164
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.AspNetCore.Session.SessionMiddleware.<Invoke>d__9.MoveNext() in D:\temp\Session-dev\Session-dev\src\Microsoft.AspNetCore.Session\SessionMiddleware.cs:line 106
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Session.SessionMiddleware.<Invoke>d__9.MoveNext() in D:\temp\Session-dev\Session-dev\src\Microsoft.AspNetCore.Session\SessionMiddleware.cs:line 123
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()
Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNetCore.Http.dll
Microsoft.AspNetCore.Server.Kestrel: Error: Connection id "0HL1I8OFS17SU": An unhandled exception was thrown by the application.
System.InvalidOperationException: Session has not been configured for this application or request.
at Microsoft.AspNetCore.Http.DefaultHttpContext.get_Session()
at Microsoft.AspNetCore.Mvc.ViewFeatures.SessionStateTempDataProvider.SaveTempData(HttpContext context, IDictionary`2 values) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\ViewFeatures\SessionStateTempDataProvider.cs:line 57
at Microsoft.AspNetCore.Mvc.ViewFeatures.TempDataDictionary.Save() in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\ViewFeatures\TempDataDictionary.cs:line 166
at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.SaveTempDataFilter.SaveTempData(IActionResult result, ITempDataDictionaryFactory factory, HttpContext httpContext) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\Internal\SaveTempDataFilter.cs:line 91
at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.SaveTempDataFilter.<>c.<OnResultExecuting>b__5_0(Object state) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\Internal\SaveTempDataFilter.cs:line 57
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame.<FireOnStarting>d__178.MoveNext()
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: Error: An exception was thrown attempting to display the error page.
System.ObjectDisposedException: The response has been aborted due to an unhandled application exception. ---> System.InvalidOperationException: Session has not been configured for this application or request.
at Microsoft.AspNetCore.Http.DefaultHttpContext.get_Session()
at Microsoft.AspNetCore.Mvc.ViewFeatures.SessionStateTempDataProvider.SaveTempData(HttpContext context, IDictionary`2 values) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\ViewFeatures\SessionStateTempDataProvider.cs:line 57
at Microsoft.AspNetCore.Mvc.ViewFeatures.TempDataDictionary.Save() in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\ViewFeatures\TempDataDictionary.cs:line 166
at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.SaveTempDataFilter.SaveTempData(IActionResult result, ITempDataDictionaryFactory factory, HttpContext httpContext) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\Internal\SaveTempDataFilter.cs:line 91
at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.SaveTempDataFilter.<>c.<OnResultExecuting>b__5_0(Object state) in D:\temp\Mvc-dev\src\Microsoft.AspNetCore.Mvc.ViewFeatures\Internal\SaveTempDataFilter.cs:line 57
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame.<FireOnStarting>d__178.MoveNext()
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame.ThrowResponseAbortedException()
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame.<ProduceStartAndFireOnStartingAwaited>d__194.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame.Write(ArraySegment`1 data)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameResponseStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.StreamWriter.Write(String value)
at Microsoft.Extensions.RazorViews.BaseView.Write(String value)
at Microsoft.AspNetCore.Diagnostics.RazorViews.ErrorPage.<ExecuteAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Extensions.RazorViews.BaseView.<ExecuteAsync>d__29.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()
Microsoft.AspNetCore.Server.Kestrel: Error: Connection id "0HL1I8OFS17SU": An unhandled exception was thrown by the application.
Finally I figured it out what's the issue after digging into the source code. Asp.Net Core MVC not supported complex data type for TempData currently. It only support string for now. It through this exception while serialize data, if we pass other then string.
The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer' cannot serialize an object of type 'MvcSandbox.Controllers.Alert'.
I serialize my list to json and then save in TempData.
Here is how I did this. I create extension method to add and retrieve data from TempData.
const string Alerts = "Alerts";
public static List<Alert> GetAlert(this ITempDataDictionary tempData)
{
CreateAlertTempData(tempData);
return DeserializeAlerts(tempData[Alerts] as string);
}
public static void CreateAlertTempData(this ITempDataDictionary tempData)
{
if (!tempData.ContainsKey(Alerts))
{
tempData[Alerts] = "";
}
}
public static void AddAlert(this ITempDataDictionary tempData, Alert alert)
{
if(alert == null)
{
throw new ArgumentNullException(nameof(alert));
}
var deserializeAlertList = tempData.GetAlert();
deserializeAlertList.Add(alert);
tempData[Alerts] = SerializeAlerts(deserializeAlertList);
}
public static string SerializeAlerts(List<Alert> tempData)
{
return JsonConvert.SerializeObject(tempData);
}
public static List<Alert> DeserializeAlerts(string tempData)
{
if(tempData.Length == 0)
{
return new List<Alert>();
}
return JsonConvert.DeserializeObject<List<Alert>>(tempData);
}
Add Alert it TempData
tempData.AddAlert(new Alert(AlertClass, Message));
Finally get 'TempDatainView' and display.
#if (TempData.GetAlert().Count > 0)
{
<div class="alert-container">
#foreach (var alert in TempData.GetAlert())
{
<div class="alert #alert.AlertClass alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#alert.Message
</div>
}
</div>
}
Did you configure Session? TempData is using session behind the scenes.
Project.json
"Microsoft.AspNetCore.Session": "1.1.0"
Here is the Startup.cs file. - ConfigureServices method
public void ConfigureServices(IServiceCollection services)
{
services.AddSession();
services.AddMvc();
}
And Configure method.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Now try with TempData, it will work.
And you can set the environment with set ASPNETCORE_ENVIRONMENT=Development environment variable.
This is what I use to enable Session and Temp data on Core Runtime 2.0.6.
ConfigureServices Section of Startup
// Add MVC service.
services.AddMvc(config =>
{
// Configure global usage of antiforgery tokens.
config.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
})
.AddSessionStateTempDataProvider();
// Adds the ability to use session variables.
services.AddSession(options =>
{
options.Cookie.HttpOnly = true;
});

Magento API error --- SoapHeaderException: Procedure 'login' not present

I am lost. I do not even know where to begin. This is the error I am getting:
Procedure 'login' not present
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.Services.Protocols.SoapHeaderException: Procedure 'login' not present
Source Error:
Line 375: service.Url = account.APIURL;
Line 376:
Line 377: string sessionId = service.login(account.APIUser, account.APIPassword);
Line 378:
Line 379: var orders = service.salesOrderList(sessionId, InitialiseSOAPOrderCriteria(account.TriggerOrderStatus));
Source File: c:\inetpub\wwwroot\UAT.SFSystem\Settings\ChannelHeader.ascx.cs Line: 377
Stack Trace:
[SoapHeaderException: Procedure 'login' not present]
System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) +1772421
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +345
Adapters.MagentoSOAP.MagentoSOAP.MagentoService.login(String username, String apiKey) in C:\Work\WebCatch\SF\StoreFeeder\Middlewares\SFMWMagento\Adapters.MagentoSOAP\Web References\MagentoSOAP\Reference.cs:663
Settings_ChannelHeader.magentoTestConnection(String channelGuid) in c:\inetpub\wwwroot\UAT.SFSystem\Settings\ChannelHeader.ascx.cs:377
Settings_ChannelHeader.btnTestConnection_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot\UAT.SFSystem\Settings\ChannelHeader.ascx.cs:154
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3707
I was getting the same error while using the v2 magento api, but problem resolved when I switched back to v1 soap api of magento