Updating multiple rows Linq vs SQL

后端 未结 5 619
生来不讨喜
生来不讨喜 2021-01-01 17:06

Some time ago I wrote a piece of code to update multiple rows in a database table. The code was like this

var db = new MyDataContext();
db.Execute(\"UPDATE D         


        
相关标签:
5条回答
  • 2021-01-01 17:32

    I'd say it depends on whether efficiency or abstraction from the database is more important to you. The SQL way is going to create a dependency in your code that is harder to track, but is more efficient. The LINQ sample quoted removes the dependency on hand-coded SQL but involves at least 2 queries and some server side processing.

    0 讨论(0)
  • 2021-01-01 17:41

    PLINQO has implemented the batch updates and deletes and each entity generated by plinqo can use the batch update and delete operations.

    context.Task.Update(t => t.Id == 1, t2 => new Task {StatusId = 2});
    

    This will perform an Update Task Set StatusId = 2 Where Id = 1

    0 讨论(0)
  • 2021-01-01 17:53

    Check the approach used in this article:

    • Batch Updates and Deletes with LINQ to SQL
    0 讨论(0)
  • 2021-01-01 17:58
    for (int i = 0; i < pListOrderDetail.Count; i++)
    {
        for (int j = 0; j < stempdata.Count; j++)
        {
            pListOrderDetail[i].OrderID = pOrderID;
            pListOrderDetail[i].ProductID = stempdata[j].pProductID;
            pListOrderDetail[i].Quantity = stempdata[j].pQuantity;
            pListOrderDetail[i].UnitPrice = stempdata[j].pUnitPrice;
            pListOrderDetail[i].Discount = stempdata[j].pDiscount;
            db.SubmitChanges();
            break;
        }
        continue;
    }
    
    0 讨论(0)
  • 2021-01-01 17:59

    The Linq-to-SQL version is going to SELECT every row from the details table that matches the query, pull them into memory, and create objects for them. Then when it applies the updates, it will use a separate UPDATE statement for each object, and will (by default) include a WHERE clause that checks the value of every column to make sure it hasn't changed since you did the SELECT. If the row has changed, Linq will throw an exception.

    The Linq version of the code is going to be MUCH slower (think 100x or 1000x slower), and expose you to additional exceptions.

    The SQL version might be a bit harder to maintain as you refactor code in the future, but it will make a world of difference to your database.

    I generally feel that Linq-to-SQL is great for selects and individual updates, and maybe for small batches the database would be fast enough that the extra queries wouldn't a problem, but I would have to think carefully before I used Linq for large batches, or on a web server.

    0 讨论(0)
提交回复
热议问题