What is the recommended practice to update or delete multiple entities in EntityFramework?

后端 未结 3 530
滥情空心
滥情空心 2021-01-17 07:29

In SQL one might sometimes write something like

DELETE FROM table WHERE column IS NULL

or

UPDATE table SET column1=valu         


        
相关标签:
3条回答
  • 2021-01-17 07:58

    EF doesn't have support for batch updates or deletes but you can simply do:

    db.Database.ExecuteSqlCommand("DELETE FROM ...", someParameter);
    

    Edit:

    People who really want to stick with LINQ queries sometimes use workaround where they first create select SQL query from LINQ query:

    string query = db.Table.Where(row => row.Column == null).ToString();
    

    and after that find the first occurrence of FROM and replace the beginning of the query with DELETE and execute result with ExecuteSqlCommand. The problem with this approach is that it works only in basic scenarios. It will not work with entity splitting or some inheritance mapping where you need to delete two or more records per entity.

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

    Entity Framework Extended Library helps to do this.

    Delete

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

    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"});
    

    https://github.com/loresoft/EntityFramework.Extended

    0 讨论(0)
  • 2021-01-17 08:12

    Take a look to Entity Framework Extensions (Multiple entity updates). This project allow set operations using lambda expressions. Samples from doc:

    this.Container.Devices.Delete(o => o.Id == 1);
    
    this.Container.Devices.Update(
         o => new Device() { 
            LastOrderRequest = DateTime.Now, 
            Description = o.Description + "teste"
         }, 
         o => o.Id == 1);
    

    Digging EFE project source code you can see how automatize @Ladislav Mrnka second approach also adding setting operations:

        public override string GetDmlCommand()
        {
            //Recover Table Name
    
            StringBuilder updateCommand = new StringBuilder();
            updateCommand.Append("UPDATE ");
            updateCommand.Append(MetadataAccessor.GetTableNameByEdmType(
                                      typeof(T).Name));
            updateCommand.Append(" ");
            updateCommand.Append(setParser.ParseExpression());
            updateCommand.Append(whereParser.ParseExpression());
    
            return updateCommand.ToString();
        }
    

    Edited 3 years latter

    Take a look to this great answer: https://stackoverflow.com/a/12751429

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