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

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.

Related

Failed Executing DbCommand during Entity Framework migration in .NetCORE Web API --

I created a .netcore webapi targeting framework 3.1. Added the required classes and code in ApplicationUser and ApplicationDbContext and in startup services.AddDbContext<..........
Then I ran command add-migration IniCr which built and ran ok.
But when I ran the update-database console window shows the following error:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (21ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [AspNetUsers] (
[Id] nvarchar(450) NOT NULL,
[UserName] nvarchar(256) NULL,
[NormalizedUserName] nvarchar(256) NULL,
[Email] nvarchar(256) NULL,
[NormalizedEmail] nvarchar(256) NULL,
[EmailConfirmed] bit NOT NULL,
[PasswordHash] nvarchar(max) NULL,
[SecurityStamp] nvarchar(max) NULL,
[ConcurrencyStamp] nvarchar(max) NULL,
[PhoneNumber] nvarchar(max) NULL,
[PhoneNumberConfirmed] bit NOT NULL,
[TwoFactorEnabled] bit NOT NULL,
[LockoutEnd] datetimeoffset NULL,
[LockoutEnabled] bit NOT NULL,
[AccessFailedCount] int NOT NULL,
CONSTRAINT [PK_AspNetUsers] PRIMARY KEY ([Id])
);
Failed executing DbCommand (21ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [AspNetUsers] (
[Id] nvarchar(450) NOT NULL,
[UserName] nvarchar(256) NULL,
[NormalizedUserName] nvarchar(256) NULL,
[Email] nvarchar(256) NULL,
[NormalizedEmail] nvarchar(256) NULL,
[EmailConfirmed] bit NOT NULL,
[PasswordHash] nvarchar(max) NULL,
[SecurityStamp] nvarchar(max) NULL,
[ConcurrencyStamp] nvarchar(max) NULL,
[PhoneNumber] nvarchar(max) NULL,
[PhoneNumberConfirmed] bit NOT NULL,
[TwoFactorEnabled] bit NOT NULL,
[LockoutEnd] datetimeoffset NULL,
[LockoutEnabled] bit NOT NULL,
[AccessFailedCount] int NOT NULL,
CONSTRAINT [PK_AspNetUsers] PRIMARY KEY ([Id])
);
System.AggregateException: An error occurred while writing to logger(s). (Cannot open log for source '.NET Runtime'. You may not have write access.)
---> System.InvalidOperationException: Cannot open log for source '.NET Runtime'. You may not have write access.
---> System.ComponentModel.Win32Exception (1722): The RPC server is unavailable.
--- End of inner exception stack trace ---
at System.Diagnostics.EventLogInternal.OpenForWrite(String currentMachineName)
at System.Diagnostics.EventLogInternal.InternalWriteEvent(UInt32 eventID, UInt16 category, EventLogEntryType type, String[] strings, Byte[] rawData, String currentMachineName)
at System.Diagnostics.EventLogInternal.WriteEvent(EventInstance instance, Byte[] data, Object[] values)
at System.Diagnostics.EventLog.WriteEvent(EventInstance instance, Object[] values)
at Microsoft.Extensions.Logging.EventLog.WindowsEventLog.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category)
at Microsoft.Extensions.Logging.EventLog.EventLogLogger.WriteMessage(String message, EventLogEntryType eventLogEntryType, Int32 eventId)
at Microsoft.Extensions.Logging.EventLog.EventLogLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
at Microsoft.Extensions.Logging.Logger.<Log>g__LoggerLog|12_0[TState](LogLevel logLevel, EventId eventId, ILogger logger, Exception exception, Func`3 formatter, List`1& exceptions, TState& state)
--- End of inner exception stack trace ---
at Microsoft.Extensions.Logging.Logger.ThrowLoggingError(List`1 exceptions)
at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
at Microsoft.Extensions.Logging.LoggerMessage.<>c__DisplayClass10_0`6.<Define>b__0(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception)
at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition`6.Log[TLoggerCategory](IDiagnosticsLogger`1 logger, WarningBehavior warningBehavior, TParam1 arg1, TParam2 arg2, TParam3 arg3, TParam4 arg4, TParam5 arg5, TParam6 arg6)
at Microsoft.EntityFrameworkCore.Diagnostics.RelationalLoggerExtensions.LogCommandError(IDiagnosticsLogger`1 diagnostics, DbCommand command, TimeSpan duration, EventDefinition`6 definition)
at Microsoft.EntityFrameworkCore.Diagnostics.RelationalLoggerExtensions.CommandError(IDiagnosticsLogger`1 diagnostics, IRelationalConnection connection, DbCommand command, DbContext context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, Exception exception, DateTimeOffset startTime, TimeSpan duration)
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)
An error occurred while writing to logger(s). (Cannot open log for source '.NET Runtime'. You may not have write access.)
When I check my mssql server I see a new db created as per the name I gave in appsettinngs.json but only with 1 table - efmigrationhistory.
Why such? What mistake did I make? What needs to be done to get the migration going and create the full database with aspnet identity? Please suggest the correction;
Some help needed.
I have resolved the issue.
I ran the query
select ##version
and found that I was running version 2005 of the database engine which does not have the data type datetimeoffset.
I went through the installation process of Sql Server 2019.
And then ran the code migrations of my project allover again. It completed just fine! No issues whatsoever anymore in doing code-migrations,
Does running visual studio as administrator solve or changes the error?
You have a logger configured which writes to Windows Event log. The account you are running your migrations under does not have access to writing logs, which is why the whole operation is failing.
Either grant it the necessary permissions or don't write to event log.
P.S.: Since your application is likely cross-platform otherwise, I question the wisdom of writing to Windows specific logs.

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?

AspNetCore.Identity using PostgreSQL: how to create structure?

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));
}
}
}

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.

Spring Mybatis Oracle function call

I'm getting following error while calling the oracle function...
org.springframework.jdbc.UncategorizedSQLException:
### Error querying database. Cause: java.sql.SQLException: Non supported SQL92 token at position: 1:
### The error may exist in file [C:\Users\pkr\rpt\bin\dbmappers\MyMapper.xml]
### The error may involve com.pkr.tpy.rpt.dao.MyDao.resetRecs-Inline
### The error occurred while setting parameters
### SQL: { ? = call actions.reset_recs(?, ?, ?, ?) }
### Cause: java.sql.SQLException: Non supported SQL92 token at position: 1:
; uncategorized SQLException for SQL []; SQL state [99999]; error code [17034]; Non supported SQL92 token at position: 1: ; nested exception is java.sql.SQLException: Non supported SQL92 token at position: 1:
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:84)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:447)
at com.sun.proxy.$Proxy37.selectOne(Unknown Source)
Here is my mapper.xml
<select id="resetRecs" resultType="String" statementType="CALLABLE">
{
#{retVal,mode=OUT,jdbcType=VARCHAR} = call actions.reset_recs(#{xCode, jdbcType=DECIMAL,mode=IN},
#{yCode,jdbcType=DECIMAL,mode=IN},
#{xyzNum,jdbcType=DECIMAL,mode=IN},
#{src,jdbcType=VARCHAR,mode=IN})
}
</select>
DAO Interface:
String resetRecs(#Param("xCode") int xCode,
#Param("yCode") int yCode,
#Param("xyzNum") int xyzNum, #Param("xyzSrc") String xyzSource,
#Param("retVal") String retVal);
I'm using Mybatis 3.4.0, any help would be greatly appreciated.
I was able to fix this when I updated my mapper call statement in one line.
<select id="resetRecs" resultType="String" statementType="CALLABLE">
{#{retVal,mode=OUT,jdbcType=VARCHAR} = call actions.reset_recs(#{xCode, jdbcType=DECIMAL,mode=IN},#yCode,jdbcType=DECIMAL,mode=IN},#xyzNum,jdbcType=DECIMAL,mode=IN},#{src,jdbcType=VARCHAR,mode=IN})}