Update Object List via Entity Framework

Asked

Viewed 692 times

0

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

Today I have a list of objects like

Formatacao_RelatorioLinhaDeletada

and perform a foreach on this list, picking 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 wonder if I can perform an entire list attach as if we were running an SQL as below that updates multiple records with a single Update:

UPDATE TABELA SET a = 2 WHERE TESTE > 0

I await the discussion of the people but already thank!

  • there are ways to do this, one is with Pure SQL by Entity Framework, another is to bring the data and changing the list giving a SavingChanges() if few records work well, everything depends on contexts if you can say something else, how you bring the list, how many records comes, want to create a method and solve this problem basically with pure SQL?

  • The list comes with many records however it is exactly the table template in Entity

1 answer

2


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

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

Install-Package Entityframework.Extended

Then just update. An example would be:

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

This way it will update all table data Task where Teste > 0.

If you want to do it in your hand, you can always use the 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.

  • The problem is that I already have the list I just wanted to update it.. In this case the Where of the above example would not meet.

  • @Arthurzanini Update in the database or only in the list items to do some other operation?

  • would be an update in the bank itself

  • @Arthurzanini thus updates the bank. But it also agrees to pass a list (IQueryable), as shown in official documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.