Проверка первичного ключа EF Core посредством обработки исключенийC#

Место общения программистов C#
Ответить
Anonymous
 Проверка первичного ключа EF Core посредством обработки исключений

Сообщение Anonymous »


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
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»