Update object list via entity Framework

0

Good morning! I wanted to ask for your help just to see if there is a better way to do it.

Today I have a list of objects of type

  

Formation_RelationLineDeletted

and I make a foreach in this list, taking item by item giving the attach and saving the modifications in the bank according to the code below:

db.Formatacao_RelatorioLinhaDeletada.Attach(obj);
db.Entry<Formatacao_RelatorioLinhaDeletada>(obj).State = EntityState.Modified;

return (db.SaveChanges() > 0);

I would like to know if I can perform an attach to the whole list as if we were executing a SQL as below that updates multiple records with a single Update:

UPDATE TABELA SET a = 2 WHERE TESTE > 0

I hope the discussion of the galera but thank you already!

    
asked by anonymous 04.10.2016 / 17:22

1 answer

2

A simple way to do this is to use the Entity Framework Extended .

First, just install the library via the following NuGet command:

  

Install-Package EntityFramework.Extended

Then, just do the update. An example would be:

context.Tasks.Where(t => t.Teste > 0)
              .Update(t => new Task { a = 2 });

This will update all the data in the Task table where Teste > 0 .

If you want to do this, you can always use Database.ExecuteSqlCommand . That way your code would look something like this:

var sql = "UPDATE [TABELA] SET a = 2 WHERE TESTE > 0";
context.Database.ExecuteSqlCommand(sql);

If you want to pass parameters, this question has several examples of how to do this.

    
04.10.2016 / 18:15