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

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.

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?

EF Core - Key (Id)=(0) is not present in table

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.

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.

JPA access Postgresql 9.4 generated sequence "id" not exist error

I had a project needs to set up SMS gateway that works with JAVA-EE project. GAMMU 1.36.0 was selected.
backend DB is Postgresql 9.4, table inbox and sequence were created to hold in come SMS.
inbox created by use:
CREATE TABLE inbox (
"UpdatedInDB" timestamp(0) WITHOUT time zone NOT NULL DEFAULT LOCALTIMESTAMP(0),
"ReceivingDateTime" timestamp(0) WITHOUT time zone NOT NULL DEFAULT LOCALTIMESTAMP(0),
"Text" text NOT NULL,
"SenderNumber" varchar(20) NOT NULL DEFAULT '',
"Coding" varchar(255) NOT NULL DEFAULT 'Default_No_Compression',
"UDH" text NOT NULL,
"SMSCNumber" varchar(20) NOT NULL DEFAULT '',
"Class" integer NOT NULL DEFAULT '-1',
"TextDecoded" text NOT NULL DEFAULT '',
"ID" serial PRIMARY KEY,
"RecipientID" text NOT NULL,
"Processed" boolean NOT NULL DEFAULT 'false',
CHECK ("Coding" IN
('Default_No_Compression','Unicode_No_Compression','8bit','Default_Compression','Unicode_Compression')));
id is a sequence number hold in:
--CREATE SEQUENCE inbox_ID_seq;
table structure looks like:
smsd-> \d inbox
Table "public.inbox"
Column | Type | Modifiers
-------------------+--------------------------------+----------------------------------------------------------------
UpdatedInDB | timestamp(0) without time zone | not null default ('now'::text)::timestamp(0) without time zone
ReceivingDateTime | timestamp(0) without time zone | not null default ('now'::text)::timestamp(0) without time zone
Text | text | not null
SenderNumber | character varying(20) | not null default ''::character varying
Coding | character varying(255) | not null default 'Default_No_Compression'::character varying
UDH | text | not null
SMSCNumber | character varying(20) | not null default ''::character varying
Class | integer | not null default (-1)
TextDecoded | text | not null default ''::text
ID | integer | not null default nextval('"inbox_ID_seq"'::regclass)
RecipientID | text | not null
Processed | boolean | not null default false
Indexes:
"inbox_pkey" PRIMARY KEY, btree ("ID")
Check constraints:
"inbox_Coding_check" CHECK ("Coding"::text = ANY (ARRAY['Default_No_Compression'::character varying, 'Unicode_No_Compression'::character varying, '8bit'::character varying, 'Default_Compression'::character varying, 'Unicode_Compression'::character varying]::text[]))
Triggers:
update_timestamp BEFORE UPDATE ON inbox FOR EACH ROW EXECUTE PROCEDURE update_timestamp()
smsd->
Please note: column ids' position is 10 in the table.
This table is working well with GAMMU 1.36.0, send and receive SMS properly.
When I try to develop a EJB to bring the inbox information to my web application.
I am using JPA 2.1, implementation is EclipseLink 2.5.2. persistence.xml looks like:
<persistence-unit name="SmsdJPANBPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<mapping-file>com/longz/smsd/model/SmsdInboxEntity.xml</mapping-file>
<mapping-file>com/longz/smsd/model/SmsdOutboxEntity.xml</mapping-file>
<mapping-file>com/longz/smsd/model/SmsdSentitemsEntity.xml</mapping-file>
<class>com.longz.smsd.model.SmsdInboxEntity</class>
<class>com.longz.smsd.model.SmsdOutboxEntity</class>
<class>com.longz.smsd.model.SmsdSentitemsEntity</class>
<properties>
<property name="eclipselink.jdbc.url" value="jdbc:postgresql://10.0.1.100:5433/smsd"/>
<property name="eclipselink.jdbc.driver" value="org.postgresql.Driver"/>
<property name="eclipselink.jdbc.user" value="any"/>
<property name="eclipselink.jdbc.password" value="any"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
JPA entity bean defined:
#Entity
#Table(name = "inbox", schema = "public", catalog = "smsd")
#NamedQueries({
/*#NamedQuery(name = "Inbox.findAll", query = "SELECT i FROM InboxEntity i ORDER BY i.id DESC"),*/
#NamedQuery(name = "Inbox.findAll", query = "SELECT i FROM SmsdInboxEntity i order by i.id desc"),
......
public class SmsdInboxEntity implements Serializable{
......
#Id
#SequenceGenerator(name="JOB_MISFIRE_ID_GENERATOR", sequenceName="inbox_ID_seq",schema = "public", allocationSize=1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator="JOB_MISFIRE_ID_GENERATOR")
#Column(name = "ID", nullable = false, insertable = true, updatable = true)
public int getId() {
return id;
}
......
}
stateless session bean as:
#Remote(InboxEntityFacadeRemote.class)
#Stateless(mappedName= "inboxEntityFacadeEJB")
public class InboxEntityFacade extends AbstractFacade<SmsdInboxEntity> implements InboxEntityFacadeRemote {
#PersistenceContext(unitName = "SmsdJPANBPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public InboxEntityFacade() {
super(SmsdInboxEntity.class);
}
#Override
public List<SmsdInboxEntity> findAll(){
Query query = em.createNamedQuery("Inbox.findAll");
return new LinkedList<SmsdInboxEntity>(query.getResultList());
/*return super.findAll();*/
}
I tried to use findall() function to list all sms in inbox. This function will call named query statement:
#NamedQuery(name = "Inbox.findAll", query = "SELECT i FROM SmsdInboxEntity i order by i.id desc"),
Test EJB client as:
try {
Context context = new InitialContext(properties);
InboxEntityFacadeRemote inboxEnFaRemote = (InboxEntityFacadeRemote)context.lookup("inboxEntityFacadeEJB#com.longz.smsd.remote.InboxEntityFacadeRemote");
System.out.println("inboxEntityFacadeEJB found.");
List<com.longz.smsd.model.SmsdInboxEntity> todaysemails = inboxEnFaRemote.findAll();
System.out.println("Records found: "+ todaysemails.size());
todaysemails.stream().forEach((e) -> {
System.out.println(e.getTextDecoded());
});
}catch (NamingException e) {
e.printStackTrace();
}
}
Everything is work fine so far. but very strange error thrown:
run:
inboxEntityFacadeEJB found.
Exception in thread "main" javax.ejb.EJBException: EJB Exception: ; nested exception is:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
Error Code: 0
Call: SELECT ID, Class, Coding, Processed, ReceivingDateTime, RecipientID, SenderNumber, SMSCNumber, Text, TextDecoded, UDH, UpdatedInDB FROM smsd.public.inbox ORDER BY ID DESC
Query: ReadAllQuery(name="Inbox.findAll" referenceClass=SmsdInboxEntity sql="SELECT ID, Class, Coding, Processed, ReceivingDateTime, RecipientID, SenderNumber, SMSCNumber, Text, TextDecoded, UDH, UpdatedInDB FROM smsd.public.inbox ORDER BY ID DESC")
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.unwrapRemoteException(RemoteBusinessIntfProxy.java:117)
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(RemoteBusinessIntfProxy.java:92)
at com.sun.proxy.$Proxy0.findAll(Unknown Source)
at weblogicejbclient.WeblogicInboxEJBClient.main(WeblogicInboxEJBClient.java:38)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
Error Code: 0
Call: SELECT ID, Class, Coding, Processed, ReceivingDateTime, RecipientID, SenderNumber, SMSCNumber, Text, TextDecoded, UDH, UpdatedInDB FROM smsd.public.inbox ORDER BY ID DESC
Query: ReadAllQuery(name="Inbox.findAll" referenceClass=SmsdInboxEntity sql="SELECT ID, Class, Coding, Processed, ReceivingDateTime, RecipientID, SenderNumber, SMSCNumber, Text, TextDecoded, UDH, UpdatedInDB FROM smsd.public.inbox ORDER BY ID DESC")
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:378)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:469)
at com.longz.smsd.ejb.InboxEntityFacade.findAll(InboxEntityFacade.java:36)
at com.longz.smsd.ejb.InboxEntityFacadeEJB_s9wt3_InboxEntityFacadeRemoteImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionRemoteMethodInvoker.invoke(SessionRemoteMethodInvoker.java:34)
at com.longz.smsd.ejb.InboxEntityFacadeEJB_s9wt3_InboxEntityFacadeRemoteImpl.findAll(Unknown Source)
at com.longz.smsd.ejb.InboxEntityFacadeEJB_s9wt3_InboxEntityFacadeRemoteImpl_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:701)
at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:231)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:527)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:523)
at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
Error Code: 0
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:682)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2002)
at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:570)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCallQueryMechanism.java:299)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQueryMechanism.java:694)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRowsFromTable(ExpressionQueryMechanism.java:2738)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRows(ExpressionQueryMechanism.java:2691)
at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:495)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1168)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1127)
at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:403)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1215)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1786)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1751)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)
... 15 more
Caused by: org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1927)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:561)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:419)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:304)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeSelect(DatabaseAccessor.java:1007)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:642)
... 35 more
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
seems PSQL trying find "id" column in position 8 instead of position 10 and actually "id" column located in position 10 in inbox table.
Any idea and advice please! Appreciated!!
Your problem is case-sensitivity: JPA works in case insensitive mode by default (i.e. it won't quote identifiers in its queries), while PostgreSQL will convert any unquoted identifiers to lower-case (this is the way PostgreSQL tries to achieve case insensitivity). But, you defined your "ID" column in case-sensitive mode (note the quotes).
An ugly workaround is, that you define your entity in a case-sensitive way:
#Column(name = "\"ID\"")
Or, you can define your table in a case-insensitive way (which is preferred):
CREATE TABLE inbox (
ID serial PRIMARY KEY
-- ...
);
Eventually. This issue was fixed by using native SQL query
Query query = em.createNativeQuery("Select * from inbox",com.longz.smsd.model.SmsdInboxEntity.class);
return new LinkedList<SmsdInboxEntity>(query.getResultList());
Seems JSQL is not 100% works in this situation.
This one will be help some one else who have the same issue.