1

I'm trying to regroup a select followed by an update in an EFCore transaction. The entity I want to update have an id (For relation between entities) and a guid (To hide my predictable Ids). I don't want to use Guid as primary key.

When a user want to update the entity, I only got the guid from my DTO, then I must retrieve the Id from database to update my entity. At the moment, it works by doing a select and an update just after, but it's not optimized because it's doing two round trips to the database. How do you manage this kind of case without having to do two round trips ?

Here is my code atm :

public void Update(EmailTemplate emailTemplate, string username)
    {
        // Beginning of transaction
        using (var transaction = _uow.BeginTransaction())
        {
            try
            {
                // Retrieving id by guid
                emailTemplate.Id = _emailTemplateRepository.GetIdByGuid(emailTemplate.Guid);

                emailTemplate.ModifiedBy = username;
                emailTemplate.ModifiedDate = DateTime.Now;

                foreach (EmailTemplateTranslation ett in emailTemplate.EmailTemplateTranslations)
                {
                    // Updating childs
                    _emailTemplateTranslationRepository.Update(ett);
                }

                // Updating entity
                _emailTemplateRepository.Update(emailTemplate);

                // SaveChanges from UnitOfWork
                _uow.Commit();

                // Transaction commit
                transaction.Commit();
            }
            catch(Exception ex)
            {
                transaction.Rollback();
            }
        }
    }

This code generate two round trips even if the select is included in the transaction.

LeRebelle
  • 11
  • 2
  • 1
    Transactions don't mean all the queries will run at once in the database. It gives certain guarantees with regards to isolation etc. (depending on isolation level). Your code is running a select, which gets data to your app, and then after some processing executes updates and commits the transaction. – juunas Sep 16 '19 at 12:01
  • Is it possible to create an EF query in the form: update ... where guid = ...? – Stefan Sep 16 '19 at 12:02
  • With EF you can't really do updates with a single round trip. You'll need to use SQL or some EF extensions which allow that. – juunas Sep 16 '19 at 12:02
  • @stefan I was looking for this kind of thing, but seems I need an EF extension to do that, as juunas stated. Thanks both of you for this fast answer. If I found an extension which can do that, I will post as an answer. – LeRebelle Sep 16 '19 at 12:52
  • I believe the answer on this thread helps with your situation: https://stackoverflow.com/questions/50844828/ef-db-savechanges-vs-dbtransaction-commit – Cardi DeMonaco Jr Sep 16 '19 at 13:02

0 Answers0