Проверка первичного ключа EF Core посредством обработки исключений ⇐ C#
-
Anonymous
Проверка первичного ключа EF Core посредством обработки исключений
I would like to insert new entries into a database without verifying that the entry already exists through a separate query (e.g. a get query etc). I have something similar to the code below and it seems like that even though I am changing the entry.Id (PK) I am not able to successfully insert the entry
since the entity is still tracked as EntityState.Added, even though the add failed due to an exception. My goal is to reduce the database requests to a minimum and I would like to prevent a primary key check before inserting. The primary keys are already predefined and not incremented by the Db itself.
public void InsertObject(DbContext dbContext, Entry entry) { while (!Add(dbContext, entry)) { entry.Id = Guid.NewGuid().ToString(); } dbContext.SaveChanges(); } public bool Add(DbContext dbContext, Entry entry) { try { dbContext.EntryTable.Add(entry); return true; } catch (DbUpdateException ex) { return false; } }
Источник: https://stackoverflow.com/questions/780 ... n-handling
I would like to insert new entries into a database without verifying that the entry already exists through a separate query (e.g. a get query etc). I have something similar to the code below and it seems like that even though I am changing the entry.Id (PK) I am not able to successfully insert the entry
since the entity is still tracked as EntityState.Added, even though the add failed due to an exception. My goal is to reduce the database requests to a minimum and I would like to prevent a primary key check before inserting. The primary keys are already predefined and not incremented by the Db itself.
public void InsertObject(DbContext dbContext, Entry entry) { while (!Add(dbContext, entry)) { entry.Id = Guid.NewGuid().ToString(); } dbContext.SaveChanges(); } public bool Add(DbContext dbContext, Entry entry) { try { dbContext.EntryTable.Add(entry); return true; } catch (DbUpdateException ex) { return false; } }
Источник: https://stackoverflow.com/questions/780 ... n-handling
Мобильная версия