Npgsql i get: 42P01: relation "sometable" does not exist - c#

I am trying to run this query via Npgsql, this query work well when i run it directly on the server because i get: Query returned successfully with no result in 15 ms.However, when i use Npgsql i get: 42P01: relation "sometable" does not exist
I know that the error is is in the INSERT statement, am i missing something ?
connection string: Host=192.168.137.47;Port=5432;UserId=postgres;Password=test;Database=pg_database;
var m_createdb_cmd = new NpgsqlCommand();
m_createdb_cmd.Connection = _connPg;
m_createdb_cmd.CommandText = psSQL;
_connPg.Open();
m_createdb_cmd.ExecuteNonQuery();
_connPg.Close();
The query
BEGIN;
CREATE TABLE "sometable" (
"test" varchar(254));
INSERT INTO "sometable" ("test") VALUES ('Hello World');
COMMIT;
The Log
2015-10-01 07:08:46 EDT ERROR: relation "sometable" does not exist at character 13
2015-10-01 07:08:46 EDT STATEMENT: INSERT INTO "sometable" ("test") VALUES ('Hello World')
p.s.:i've also looked at PostgreSQL ERROR: 42P01: relation "[Table]" does not exist does not help

This is due to a known limitation introduced in Npgsql 3.x - when sending multiple SQL statements in one command, later statements can no longer depend on entities created in earlier statements. For example, you can't create a table and then insert into it in the same command. The workaround is to simply split the table creation and the insert into two commands (note that this has nothing to do with transactions).
The issue tracking this is https://github.com/npgsql/npgsql/issues/641.

Create the table. Commit that Transaction.
Then in a separate transaction, insert the data.

I had similar problem with running the DB on docker, locally it was running fine.
The solution was to add [Table("MissingTableName")] above the class.

Related

EF 6 delete fails with The select list for the Insert statement contains more items than the insert list

My EF Remove fails with the above statement. The table (Product) has a single primary key (ProductID). Running SQL Trace produced the following SQL that causes the failure:
exec sp_executesql N'DELETE [dbo].[Product] WHERE ([ProductID] = #0)',N'#0 int',#0=620895
Full error statement:
Msg 121, Level 15, State 1, Procedure t_del_Product, Line 8 The select
list for the INSERT statement contains more items than the insert
list. The number of SELECT values must match the number of INSERT
columns.
Other similar Removes work just fine. My EDMX is fully updated against the DataSource (SQL Server 2012)
Any ideas? Anyone? Anyone?
Thanks!
UPDATE: I should have tried this earlier, but I get the same error even with a simple:
DELETE FROM Product Where ProductID = 620895
So, it is not EF.
As mentioned in my comment:
It looks like the sp is being called (possibly) when a delete occurs on dbo.Product and is producing your error. Just look on the table and see if there are triggers defined on it.
If indeed there is a trigger on the table calling this SP, then this is likely your issue and you should look into fixing the SP.

Sql Connection Catalog changes after statement

Issue:
After running an Sql command with SqlCommand() on a database that then inserts data into another database, all following statements error with ExceptionInvalid object name.
Question:
Why is this happening?
Additional Information:
I know how to fix it by adding The Temp database name before the table on the select portion but since it is being run in the context of that database that shouldn't be necessary and is not when I run the statements individually in SQL management studio
Program Logic:
Create and fill temp database (All tables ASI_...)
In context of temp database select data and then insert it into another database (#AcuDB)
Repeat Step 2 for X queries
Insertion code:
if (TempD.State == System.Data.ConnectionState.Closed) TempD.Open();
Command = new SqlCommand(temp, TempD);
Command.CommandTimeout = 0;
Command.ExecuteNonQuery();
Sample Sql being run that errors after previous similar statement:
insert into #AcuDB..Batch (CompanyID,BranchID,
Module,BatchNbr,CreditTotal,DebitTotal,ControlTotal,CuryCreditTotal,CuryDebitTotal,CuryControlTotal,CuryInfoID,LedgerID,BatchType,Status,AutoReverse,AutoReverseCopy,OrigModule,OrigBatchNbr,DateEntered,Released,Posted,LineCntr,CuryID,ScheduleID,NoteID,CreatedByID,CreatedByScreenID,CreatedDateTime,LastModifiedByID,LastModifiedByScreenID,LastModifiedDateTime,Hold,Description,Scheduled,Voided,FinPeriodID,TranPeriodID)
select 2,
1,Module,BatchNbr,CreditTotal,DebitTotal,ControlTotal,CuryCreditTotal,CuryDebitTotal,CuryControlTotal,i.CuryInfoID,
isnull((select a.LedgerID from #AcuDB..ledger a where a.LedgerCD =
b.LedgerID),0)
[LedgerID],BatchType,Status,AutoReverse,AutoReverseCopy,OrigModule,OrigBatchNbr,
DateEntered
[DateEntered],Released,Posted,LineCntr,b.CuryID,ScheduleID,NoteID,
'B5344897-037E-4D58-B5C3-1BDFD0F47BF9' [CreatedByID], '00000000'
[CreatedByScreenID], GETDATE() [CreatedDateTime],
'B5344897-037E-4D58-B5C3-1BDFD0F47BF9' [LastModifiedByID], '00000000'
[LastModifiedByScreenID], GETDATE()
[LastModifiedDateTime],Hold,Description,Scheduled,Voided,b.FinPeriodID,TranPeriodID
from Temp..ASI_GLBatch b inner join #AcuDB..CurrencyInfo i on
i.CuryEffDate = b.DateEntered cross join #AcuDB..glsetup g where
b.companyID = #CpnyCD and b.branchID = #BranchCD
Going across databases like this is always precarious due to the way SQL will try to imply contexts. In this case, unless #AcuDB contains the fully-qualified address that includes both the database and the schema, you're going to get errors because of the way you're switching contexts around. Get a reading on what #AcuDB contains and try to run the batch in a stored procedure. Set up a separate instance to sandbox the scenario if you have to. The C# end of this is going to continue to complicate things until you cut it out for a little bit and make sure your SQL is good. After you're sure it's okay, integrate it back into the C# code and work from there.

C# + MySQL + ExecuteNonQuery returns '1' on UPDATE but changes not in DB

i have a problem where i can't apparently find a solution even after hours of debugging.
I have a simple SQL command where i want to update a row with some value(the value is a text of about ~5mb), after executing the SQL Command, the 'ExecuteNonQuery()' on the C# code side, returns '1' and no exception but the changes are sometime reflected in the Database row and sometime not.
I tried debugging to see if the values that will replace the old one are correct and they are. I am using MySQL 5.5.11.
Could it be a MySQL setting or something?
Losing my mind on this problem, if you have any idea it would be greatly appreciated.
EDIT, include code:
The code is as simple as this:
cmd.CommandText = "UPDATE user SET data = #data WHERE id = #id";
then i add params to the DBCommand object for the SQL Query. The 'data' is about ~5mb big.
this command always returns '1' even if the changes are not reflected in the database(sometime it works, sometime it doesnt):
cmd.ExecuteNonQuery();
Thanks in advance!
I don't know if the mysql provider uses autocommit? If not then you have to call commit on the Transaction object you can get with BeginTransaction on the connection object.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a SQL Statement or a stored procedure called by a command of CommandType.Text. In this case, named parameters must be used.
For example:
SELECT * FROM Customers WHERE CustomerID = #CustomerID
Edit:
Just noticed this was MySQL, and while i can't find anything simliar about it quickly, i would suggest you use named parameters anyways
I had this problem and it was related to autocommit.
Problem: earlier in the app lifespan autocommit was set to 0 by another process in the app, and failed. The connection with autocommit turned off is then reused by the connection pool.
That will lead to this type of error at unpredictable times.

Can't insert to sqlite using c#, "id's are not unique" but in the sqlite app it works

My SQL query is
string stringSQL = "Insert into table(clientid, contractorid, driverid)
values (1,1,last_insert_rowid() + 1)"
ExecuteNonQuery(stringSQL)
And the error I get is:
Error: abort due to constraint
violation(clientid, contractorid,
driverid are not unique.
Btw those columns are my primary keys!
Is there an issue using SQLite's functions in c# vs 2010?
Thx I advance
From the last_insert_rowid() documentation:
The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function.
Note the "from the database connection" part... which means if there's already data in your table before you open this connection, presumably it's going to start from 0 or 1 again, and end up with a conflict. In other words, I don't think you can use this as a general way of incrementing row IDs.
I'd expect this to work if the table was empty before opening your current database connection, and if that connection is the only thing to have inserted data into that table though... you might want to test that part, just to make sure we understand what's going on.
That's assuming the docs are correct, of course - I've never actually used sqlite myself...

Linq to Entities / Entity Framework delete exception

I'm working on a WPF system which hooks onto an old legacy database using the Entity Framework. We hook onto a backup of the live data when debugging and an empty database to run tests against. I'm receiving the following error only when trying to delete from a backup of the live data.
This code:
License license = ReadLicense(id);
entities.DeleteObject(license);
entities.SaveChanges();
produces this SQL:
exec sp_executesql N'delete [dbo].[Product]
where ((([Group_ID] = #0) and ([Parent_ID] = #1)) and ([Prod_ID] = #2))',N'#0 nvarchar(32),#1 nvarchar(32),#2 nvarchar(32)',#0=N'someIdValue1',#1=N'someIdValue2',#2=N'someIdValue3'
which in turn produces this error:
Msg 208, Level 16, State 1, Procedure TrackDeletedProduct, Line 4.
Invalid object name 'DeletedRecords.dbo.Product_Deleted'.
If you change the generated SQL to a 'select' query it returns a row so, 'ReadLicense' is returning a valid entity. I can't really understand why this doesn't work, especially when it's only against live data. The 'License' entity is one of two inheriting from a base 'Product' entity.
Cheers.
From what I can see, it would appear as if your table Product has a trigger on it that will fire when you delete a row, and which calls that stored procedure TrackDeletedProduct.
That procedure will (just guessing here) try to copy the product entry to the Product_Deleted table in the DeletedRecords database, but fails on that - either that other database or the table don't seem to exist.
So I don't think this has really anything to do with ADO.NET Entity Framework or LINQ-to-Entities, but a lot with SQL Server - check your backend database configuration!
Marc

Categories