var executionStrategy = _companyContext.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
using var transaction = await _companyContext.Database.BeginTransactionAsync();
_companyContext.Set<CARILER_T>().Add(newEntity);
_companyContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT CARILER_T ON;");
await _companyContext.SaveChangesAsync();
_companyContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT CARILER_T OFF");
await transaction.CommitAsync();
});
I am getting the following errors in this and this codes
await strategy.ExecuteAsync
await _companyContext.SaveChangesAsync();
SqlException: Violation of PRIMARY KEY constraint 'PK_CARILER_T'. Cannot insert duplicate key in object 'dbo.CARILER_T'. The duplicate key value is (536154).
The statement has been terminated.
DbUpdateException: An error occurred while saving the entity changes.
See the inner exception for details.
Related
I am facing a problem when trying to update data in a firebird database.
Setup is the following:
NodeJS Server with Node-Firebird module (https://github.com/hgourvest/node-firebird) --> only allows UTF8 Charset
Firebird Server 2.5 with WIN1252 Charset (charset must also stay the same)
My update statement:
db.transaction((err, transaction) => {
if (err) return closeDB(db, transaction, err);
// Update one record by pk
console.log("do update");
const params = [];
transaction.query(`UPDATE OBJEKT
SET BEZ = 'Böckstraße'
WHERE OB_KEY = 25984`, params, (err, _) => {
// The code below is executed only when the number of parameters is less than 10
if (err) return closeDB(db, transaction, err);
transaction.query('select * from OBJEKT where OB_KEY = 12345', [1], (err, data) => {
if (err) return closeDB(db, transaction, err);
console.log(data);
// Finally simply commit the transaction
closeDB(db, transaction, err);
});
});
});
When doing the update queries, I am receiving "Cannot transliterate character between charsets" error.
When I introduce the variable with my target charset (_win1252) the update is working, but the characters are not correct: Bockstraße ends up as:
I started playing around with the collations, but yet no success. How can I map these 2 charsets correctly?
ultimately I am trying to call a callback function if my query is successfully inserted.
I was thinking of trying to get the inserted row as a result and then test if the result exists and if it matches the inserted values then it was successful -> call my cb function. I'm getting an error that there's something wrong with my query. Is there a better query for this?
var username = user.username;
var password = user.password;
var email = user.email;
client.query(
'INSERT INTO account (username, password, email) OUTPUT
INSERTED.username VALUES($1, $2, $3)',
[username, password, email], (err, res) =>{
if (err) {
console.log(err);
cb(err);
}
console.log(res); // this is undefined how do i test if it was inserted?
client.end();
});
the error that is thrown is "syntax error at or near \"OUTPUT\"
That is an invalid syntax for Postgres Insert to return a value. NO such thing as OUTPUT. Try
insert into account (username, password, email)
values($1, $2, $3) returning username;
But really why brother? If the insert doesn't work you can relay on Postgres to raise an exception; if a comparison of the returned value fails, where's the error? In the insert or the data sent, or data result compared to.
I am trying to insert record into table using entity framework. I Know how to do it and i have done but i modified the database by adding a new table "PasswordRecovery" and then i update my .edmx file and then i try to insert the record into that table
PasswordRecovery OPasswordRecovery = new PasswordRecovery
{
userId = user.Id,
url = token,
requestDateTime = DateTime.Now,
isRecoverd = false
};
context.PasswordRecoveries.Add(OPasswordRecovery);
context.SaveChanges();
But the Exception "Invalid object name 'dbo.PasswordRecoveries"
Please help me
I am creating a web service method and using apply current values in that case to update a record. I am getting exception:
Error :- An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager. Verify that the key values of the supplied object match the key values of the object to which changes must be applied.
Here is the code for the above:
TestEntities db = new TestEntities();
User user = new User();
int userId = _userRepository.Find(x => x.UserId == userid).FirstOrDefault().Id;
User existingUser = _userRepository.Find(x => x.Id == userId).SingleOrDefault();
user = _userRepository.Find(x => x.Id == userId).SingleOrDefault();
db.ApplyCurrentValues(existingUser.EntityKey.EntitySetName, user);
db.SaveChanges();
Exception comes whenever the break-point hits ApplyCurrentValues method.
In this sample console app I want to update a row in a table, and then insert another row in the same table.
The table is like this
CREATE TABLE [dbo].[Basket2](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserId] [int] NULL
) ON [PRIMARY]
CREATE UNIQUE NONCLUSTERED INDEX [IX_Basket] ON [dbo].[Basket2]
(
[UserId] ASC
)
So basically a user cannot have 2 baskets.
For reasons beyond this post baskets must not be deleted from the table. Therefore when a user needs a new basket the old one is just set to a unique number (id*-1).
The following code is a sample app that simulates the flow - and fails
private static void Main(string[] args)
{
ISessionFactory sessionFactory = CreateSessionFactory();
int userId = new Random().Next();
int basketId;
using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction(IsolationLevel.ReadUncommitted))
{
var newBasket = new Basket {UserId = userId};
basketId = (int) session.Save(newBasket);
tx.Commit();
}
using (var tx = session.BeginTransaction(IsolationLevel.ReadUncommitted))
{
var basket = session.Get<Basket>(basketId);
basket.UserId = basket.Id*-1;
session.Save(basket);
// comment in this line to make it work:
//session.Flush();
var newBasket = new Basket {UserId = userId};
session.Save(newBasket);
tx.Commit();
}
}
}
The error is:
Unhandled Exception: NHibernate.Exceptions.GenericADOException: could not insert: [ConsoleApplication1.Basket][SQL: INSERT INTO [Basket] (UserId) VALUES (?); select SCOPE_IDENTITY()] ---> System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Basket' with unique index 'IX_Basket'.
If I Flush the session (commented out lines) it works, but why is this necessary?
I would prefer not having to Flush my session and letting Commit() handle it.
You don't need to Save / Update / SaveOrUpdate any entities which are already in the session.
But you are reusing the same id again. So make sure that the session is flushed before:
using (var tx = session.BeginTransaction(IsolationLevel.ReadUncommitted))
{
var basket = session.Get<Basket>(basketId);
basket.UserId = basket.Id*-1;
// no save
//session.Save(basket);
// flush change on unique field
session.Flush();
var newBasket = new Basket {UserId = userId};
// save new item which is not in the session yet
session.Save(newBasket);
tx.Commit();
}
This is because you add the same unique value again. Of course you change the existing value before, but this is not stored to the database before the session is flushed.
The session is flushed when:
you call flush
before queries (except of Get and Load)
on commit (except you use your own ADO connection)
It is a common misunderstanding that NH performs update or insert on the database when you call Save or Update. This is not the case. Insert and update are performed when flushing the session. (There are some exceptions on that, eg. when using native ids.)