Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple records using dapper after select by uniqueidentifier

Tags:

c#

dapper

I have number of records that I have loaded from database and I want to update set couple values before I return them. The only main requirement I do not want multiple commands updating each record one by one.

Please note my ids are GUIDs(uniqueidentifier)

so far I have my code as

public IEnumerable<Person> GetUnprocessedPeople(int batchSize)
    {
        List<Queue_ImportQueue> list;
        using (IDbConnection db = OpenedConnection)
        {
            string peopleList = $"SELECT TOP({batchSize}) * FROM [dbo].[Person]";

            list = db.Query<Person>(peopleList).ToList();
            using (IDbTransaction transactionScope = db.BeginTransaction(IsolationLevel.Serializable))
            {
                string updateQuery = $"UPDATE [dbo].[Person] SET Created = GETDATE() WHERE Id ='@ids'";

                try
                {
                    db.Execute(updateQuery, new { Id = list.Select(x => x.Id) }, transactionScope);
                    transactionScope.Commit();
                }
                catch (Exception ex)
                {
                    transactionScope.Rollback();
                    throw;
                }
            }
        }
        return list;
    }
like image 891
cpoDesign Avatar asked Mar 03 '26 16:03

cpoDesign


1 Answers

OK the solution was quite simple. There is no need for specific casting. just ensure you have all arguments correct. So extract that has fixed the query for me:

            string updateQuery = $"UPDATE [dbo].[Person] SET Created = GETDATE() WHERE Id ='@Ids'";

           ...

            db.Execute(updateQuery, new { Ids = list.Select(x => x.Id) }, transactionScope);
like image 129
cpoDesign Avatar answered Mar 06 '26 06:03

cpoDesign



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!