简体   繁体   中英

How to execute manual SQL as part of SaveChanges call in Entity Framework Core?

I am looking for a way to add manual raw SQL call to standard AppDbContext interaction. Say I have following code:

Message m = new Message
{
    Title = message.Title,
    Body = message.Body,
    Date = DateTime.Now,
    Foo = "foo"
};

_context.Messages.Add(m);
// Add some manual UPDATE SQL here, like:
// UPDATE SomeOtherTable SET Foo = 'Something' WHERE SomeComplex = 'Condition'

_context.SaveChanges();

The most important thing is to make that manual SQL part of command / transaction that gets created and executed as part of SaveChanges. If there is a way to inject my modification into SQL generated by SaveChanges - that's what I'm looking for.

I use an overload for SaveChangesAsync on my DbContext base that accepts any arbitrary raw sql, the key is to wrap all the processing within a manually created transaction:

  public async Task<int> SaveChangesAsync(string customCommand,
        CancellationToken cancellationToken = default(CancellationToken),
        params object[] parameters)
    {
        using (var transaction = Database.BeginTransaction())
        {
            try
            {
                var result = await base.SaveChangesAsync(true, cancellationToken);

                await Database.ExecuteSqlCommandAsync(customCommand, parameters);
                transaction.Commit();

                return result;
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw ex.Handle();
            }
        }
    }

Note: Handle() is an extension method where I transform the t-sql exceptions into my business exceptions, so that method is not relevant here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM