0

I am hitting an API and upserting my db with the results.

Initially, it inserts all of the entities (currencies).

Then each subsequent API call updates them. Sometimes, some of the 'currencies' are no longer available and I want to set 'IsActive' to false for that 'currency'. (to keep historical data)

How do I update one field in all entities where the entities do not exist in the list without doing a loop? (is it possible?)

Tried:

foreach (var cur in context.Currencies.Where(x => !x.Symbol.Contains(apiCurrencies.Values.Select(y => y.Name).ToString())).ToList())
        {
            cur.IsActive = false;
            context.Currencies.Update(cur);
            context.SaveChanges();
        }
Beau D'Amore
  • 3,174
  • 5
  • 24
  • 56
  • Please share some code and what have you tried until now. – Rafael Herscovici Apr 27 '19 at 22:45
  • Are you saying that you are passing a list of currency objects to your API and if a record is in the DB but isn't in the list you want to set a flag in the DB to show it inactive? Could you share your code? – dpberry178 Apr 28 '19 at 00:06
  • No, i am hitting an external API to get a list of available currencies, then upserting into the database. on Upsert, I want to set any currency that no longer shows up in the API results to 'IsActive = false' in the Db. Sorry, hope this is clearer. – Beau D'Amore Apr 28 '19 at 00:10
  • 1
    You can use .ForEach(). Please refer this : https://stackoverflow.com/questions/10314552/how-to-update-the-multiple-rows-at-a-time-using-linq-to-sql – sri harsha Apr 28 '19 at 14:01
  • Why do you want to avoid a loop? You need to use a loop, but you can delay your `SaveChanges` until after the loop. – NetMage Apr 29 '19 at 21:49
  • Actually, I did not need a loop (in the way I was expecting). If you look at the comment just above by Sri Harsha, there is a link to the answer I was looking for I upvoted the comment, but since it was not a full reply, I could not mark as answer. – Beau D'Amore Apr 30 '19 at 13:01

0 Answers0