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

后端 未结 3 533
滥情空心
滥情空心 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 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

提交回复
热议问题