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.
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?
I get this error when trying to insert a value into my join table in my database:
Detail: Key (Id)=(0) is not present in table "GroceryItems".
Full error:
Executing DbCommand [Parameters=[#p0='1', #p1='fsfsasf' (Nullable = false), #p2='0', #p3='df2sssfad' (Nullable = false), #p4=NULL, #p5='0', #p6='0', #p7='yosadsfdfsaff' (Nullable = false), #p8='0', #p9='0', #p10='[{"Id":11,"IconCodePoint":23145,"Name":"sdaf"}]' (Nullable = false), #p11=NULL, #p12='fMs' (Nullable = false), #p13='ffsfffs' (Nullable = false), #p14='Beacdsfff2dfh Rd' (Nullable = false), #p15=NULL, #p16=NULL], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItems" ("Id", "Brand", "CurrentRevisionId", "Description", "Image", "IsNotVeganCount", "IsVeganCount", "Name", "Rating", "RatingsCount", "Tags")
VALUES (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9, #p10);
INSERT INTO "GroceryStores" ("City", "Name", "PlaceId", "Street", "StreetNumber", "Suburb")
VALUES (#p11, #p12, #p13, #p14, #p15, #p16)
RETURNING "Id";
info: 03/26/2021 18:07:09.846 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (6ms) [Parameters=[#p0='1', #p1='fsfsasf' (Nullable = false), #p2='0', #p3='df2sssfad' (Nullable = false), #p4=NULL, #p5='0', #p6='0', #p7='yosadsfdfsaff' (Nullable = false), #p8='0', #p9='0', #p10='[{"Id":11,"IconCodePoint":23145,"Name":"sdaf"}]' (Nullable = false), #p11=NULL, #p12='fMs' (Nullable = false), #p13='ffsfffs' (Nullable = false), #p14='Beacdsfff2dfh Rd' (Nullable = false), #p15=NULL, #p16=NULL], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItems" ("Id", "Brand", "CurrentRevisionId", "Description", "Image", "IsNotVeganCount", "IsVeganCount", "Name", "Rating", "RatingsCount", "Tags")
VALUES (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9, #p10);
INSERT INTO "GroceryStores" ("City", "Name", "PlaceId", "Street", "StreetNumber", "Suburb")
VALUES (#p11, #p12, #p13, #p14, #p15, #p16)
RETURNING "Id";
dbug: 03/26/2021 18:07:09.847 CoreEventId.ForeignKeyChangeDetected[10803] (Microsoft.EntityFrameworkCore.ChangeTracking)
The foreign key property 'GroceryStore.Id' was detected as changed from '-2147482642' to '8' for entity with key '{Id: 8}'.
dbug: 03/26/2021 18:07:09.847 CoreEventId.ForeignKeyChangeDetected[10803] (Microsoft.EntityFrameworkCore.ChangeTracking)
The foreign key property 'GroceryItemGroceryStore.EstablishmentId' was detected as changed from '-2147482642' to '8' for entity with key '{VeganItemId: 1, EstablishmentId: 8}'.
dbug: 03/26/2021 18:07:09.847 RelationalEventId.DataReaderDisposing[20300] (Microsoft.EntityFrameworkCore.Database.Command)
The foreign key property 'GroceryItemGroceryStore.EstablishmentId' was detected as changed from '-2147482642' to '8' for entity with key '{VeganItemId: 1, EstablishmentId: 8}'.
dbug: 03/26/2021 18:07:09.847 RelationalEventId.DataReaderDisposing[20300] (Microsoft.EntityFrameworkCore.Database.Command)
A data reader was disposed.
dbug: 03/26/2021 18:07:09.847 RelationalEventId.CommandCreating[20103] (Microsoft.EntityFrameworkCore.Database.Command)
Creating DbCommand for 'ExecuteReader'.
dbug: 03/26/2021 18:07:09.847 RelationalEventId.CommandCreated[20104] (Microsoft.EntityFrameworkCore.Database.Command)
Created DbCommand for 'ExecuteReader' (0ms).
dbug: 03/26/2021 18:07:09.847 RelationalEventId.CommandExecuting[20100] (Microsoft.EntityFrameworkCore.Database.Command)
Executing DbCommand [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (7ms) [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
Microsoft.EntityFrameworkCore.Database.Command: Error: Failed executing DbCommand (7ms) [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
fail: 03/26/2021 18:07:09.858 RelationalEventId.CommandError[20102] (Microsoft.EntityFrameworkCore.Database.Command)
Failed executing DbCommand (7ms) [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
dbug: 03/26/2021 18:07:09.883 RelationalEventId.TransactionDisposed[20204] (Microsoft.EntityFrameworkCore.Database.Transaction)
Disposing transaction.
dbug: 03/26/2021 18:07:09.883 RelationalEventId.ConnectionClosing[20002] (Microsoft.EntityFrameworkCore.Database.Connection)
Closing connection to database 'vepo_dev_db' on server 'tcp://localhost:5432'.
dbug: 03/26/2021 18:07:09.883 RelationalEventId.ConnectionClosed[20003] (Microsoft.EntityFrameworkCore.Database.Connection)
Microsoft.EntityFrameworkCore.Database.Command: Error: Failed executing DbCommand (7ms) [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
fail: 03/26/2021 18:07:09.858 RelationalEventId.CommandError[20102] (Microsoft.EntityFrameworkCore.Database.Command)
Failed executing DbCommand (7ms) [Parameters=[#p17='8', #p18='1', #p19='0', #p20='0', #p21='0', #p22='2'], CommandType='Text', CommandTimeout='30']
INSERT INTO "GroceryItemGroceryStores" ("EstablishmentId", "VeganItemId", "Id", "InEstablishmentCount", "NotInEstablishmentCount", "Price")
VALUES (#p17, #p18, #p19, #p20, #p21, #p22);
dbug: 03/26/2021 18:07:09.883 RelationalEventId.TransactionDisposed[20204] (Microsoft.EntityFrameworkCore.Database.Transaction)
Disposing transaction.
dbug: 03/26/2021 18:07:09.883 RelationalEventId.ConnectionClosing[20002] (Microsoft.EntityFrameworkCore.Database.Connection)
Closing connection to database 'vepo_dev_db' on server 'tcp://localhost:5432'.
dbug: 03/26/2021 18:07:09.883 RelationalEventId.ConnectionClosed[20003] (Microsoft.EntityFrameworkCore.Database.Connection)
Closed connection to database 'vepo_dev_db' on server 'tcp://localhost:5432'.
fail: Microsoft.EntityFrameworkCore.Update[10000]
An exception occurred in the database while saving changes for context type 'Vepo.Data.VepoContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> Npgsql.PostgresException (0x80004005): 23503: insert or update on table "GroceryItemGroceryStores" violates foreign key constraint "FK_GroceryItemGroceryStores_GroceryItems_Id"
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)
2
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
2
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
Exception data:
Severity: ERROR
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
Exception data:
Severity: ERROR
SqlState: 23503
MessageText: insert or update on table "GroceryItemGroceryStores" violates foreign key constraint "FK_GroceryItemGroceryStores_GroceryItems_Id"
Detail: Key (Id)=(0) is not present in table "GroceryItems".
SchemaName: public
TableName: GroceryItemGroceryStores
ConstraintName: FK_GroceryItemGroceryStores_GroceryItems_Id
File: ri_triggers.c
Line: 3266
Routine: ri_ReportViolation
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
The 3 tables are GroceryItems, GroceryStores, and the join table GroceryItemGroceryStores.
Here is my code using the fluent API to set up a many to many relationship.
modelBuilder.Entity<GroceryStore>(gs =>
{
gs.HasIndex(gs => gs.PlaceId).IsUnique();
gs
.HasMany(s => s.VeganItems)
.WithMany(vi => vi.Establishments)
.UsingEntity<GroceryItemGroceryStore>
(gigs => gigs.HasOne<GroceryItem>().WithMany().HasForeignKey("Id"),
gigs => gigs.HasOne<GroceryStore>().WithMany().HasForeignKey("Id"));
});
Here are my actual database tables:
It doesn't look like this error should exist, GroceryItems has a column Id which is the primary key. Why does the error occur?
Here is the controller endpoint that runs:
// POST: api/GroceryItemGroceryStores
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<GroceryItemGroceryStore>> PostGroceryItemGroceryStore(GroceryItemGroceryStore groceryItemGroceryStore)
{
_context.GroceryItemGroceryStores.Add(groceryItemGroceryStore);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (GroceryItemGroceryStoreExists(groceryItemGroceryStore.VeganItemId))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtAction("GetGroceryItemGroceryStore", new { id = groceryItemGroceryStore.VeganItemId }, groceryItemGroceryStore);
}
JSON payload sent:
{
"veganItem": {
"name": "yosadsfdfsaff",
"brand": "fsfsasf",
"description": "df2sssfad",
"tags": [
{
"name": "sdaf",
"id": "11",
"iconCodePoint": 23145
}
]
},
"establishment": {
"name": "fMs",
"street": "Beacdsfff2dfh Rd",
"placeId": "ffsfffs"
},
"price": 2.00
}
debugger of class instance being inserted:
I have found some more details to the error - It seems to be performing an update if you see the error (even though I am just doing .Add() to add to the database:
When I try to insert a GroceryItem to the GroceryItem table nothing goes in and it returns an empty array with no errors.
It kinda seems to me like the .Add() is performing the wrong thing (update instead of insert). I have added the raw SQL into the error near the top of the question.
Removing .HasForeignKey("Id") made it work.
modelBuilder.Entity<GroceryStore>(gs =>
{
gs.HasIndex(gs => gs.PlaceId).IsUnique();
gs.HasMany(gs => gs.VeganItems)
.WithMany(vi => vi.Establishments)
.UsingEntity<GroceryItemGroceryStore>
(gigs => gigs.HasOne<GroceryItem>().WithMany(),
gigs => gigs.HasOne<GroceryStore>().WithMany());
});
I thought I needed the HasForeignKey because my database had all these foreign key constraints with VeganItemId and EstablishmentId. I thought that it was expecting my primary keys to be VeganItemId and EstablishmentId:
But I suppose the (Id) at the end of all of those means it is just Id after all.
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.
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})}