Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple rows in iQueryable

Given this table:

enter image description here

I need to update the Rate and Average for all 4 rows.

var currency = Context.Set<Currency>().Select(c => c);

That will create currency as an iQueryable. But now I'm having trouble envisioning how to formulate the update statement to update Rate and Average in all four rows.

What I need to do is the equivalent of this:

update Currencies set rate = 1.7, Average = 1.1 where CurrencyId = 1
update Currencies set rate = 2.5, Average = 2.1 where CurrencyId = 2
update Currencies set rate = 3.1, Average = 3.1 where CurrencyId = 3
update Currencies set rate = 42.7, Average = 42.1 where CurrencyId = 4
like image 963
Casey Crookston Avatar asked Aug 02 '26 02:08

Casey Crookston


2 Answers

Simple approach would be:

var currency1 = Context.Currency.Find(1);
curreny1.Rate = 1.7;
currency1.Average = 1.1;
//do the same for other currencies and finally save changes
Context.SaveChanges();

In case you want to avoid additional GET call to database to get the currency object using id, then

var currency1 = new Currency{CurrenyId = 1, Rate = 1.7, Average = 1.1 };   

var entry1 = Context.Entry(currency1);
entry1.Property(p=> p.Rate).IsModified = true;
entry1.Property(p=> p.Average).IsModified = true;

Context.SaveChanges();
like image 174
Developer Avatar answered Aug 03 '26 19:08

Developer


Maybe you can just use IEnumerable.

var currencies = Context.Set<Currency>().Select(c => c);
// var currencies = Context.Set<Currency>()Where(c => somecondition(c));

foreach(var c in currencies.ToList())
{
    c.Rate = ComputeRate(c);
    c.Average = ComputeAverage(c);
}

Context.SaveChanges();
like image 33
Pedro Perez Avatar answered Aug 03 '26 17:08

Pedro Perez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!