Entity framework update one column by increasing the current value by one without select

前端 未结 2 1836
刺人心
刺人心 2020-12-30 09:56

What I want to achieve is the simple sql query: UPDATE TABLE SET COLUMN = COLUMN + 1

Is there a way to make it happen without loading all records (t

相关标签:
2条回答
  • 2020-12-30 10:13

    Here is the solution. You can use the following code:

    context.Table.Where(x => x.Field1 > 0).Update(y => new Table { Field2 = y.Field2 + 1 });
    

    hope that it helps.

    0 讨论(0)
  • 2020-12-30 10:34

    With pure EF, you are right: you have to load the entities one by one, set the property, and save. Very inefficient.

    The 2 alternatives that I know of are:

    1. Provide raw SQL to execute the UPDATE statement as you want it.
    2. Use the EntityFramework.Extended library (https://github.com/loresoft/EntityFramework.Extended), which supports both bulk UPDATEs and DELETEs with a natural EF feel.

    Quote from their main page:

    Batch Update and Delete

    A current limitations of the Entity Framework is that in order to update or delete an entity you have to first retrieve it into memory. Now in most scenarios this is just fine. There are however some senerios where performance would suffer. Also, for single deletes, the object must be retrieved before it can be deleted requiring two calls to the database. Batch update and delete eliminates the need to retrieve and load an entity before modifying it.

    Deleting

    //delete all users where FirstName matches
    context.Users.Where(u => u.FirstName == "firstname").Delete();
    

    Update

    //update all tasks with status of 1 to status of 2
    context.Tasks.Update(
        t => t.StatusId == 1, 
        t2 => new Task {StatusId = 2});
    
    //example of using an IQueryable as the filter for the update
    var users = context.Users.Where(u => u.FirstName == "firstname");
    context.Users.Update(users, u => new User {FirstName = "newfirstname"});
    
    0 讨论(0)
提交回复
热议问题