Saturday, February 2, 2019

Doctor up n number of records in Entity Framework 6's code first paradigm.

foreach (var card in _db.Cards.Where(c => c.Suit == suit))
{
   card.Digit = digit;
}
_db.SaveChanges();

 
 

What is above works and what is below does not.

_db.Cards.Where(c => c.Suit == suit).ForEachAsync(c => { c.Digit = digit; });
_db.SaveChanges();

 
 

The .ForEachAsync approach will break because the code will run before the .Where can bring records back from the database. You do not want to chain things in such a manner. You also don't want to break records to edit off of the context and reattach them with .Attach as seen below as that did not work for me either.

List <Card> cards = _db.Cards.Where(c => c.Suit == suit).ToList();
cards.ForEach(c =>
{
   c.Digit = digit;
   _db.Cards.Attach(c);
});
_db.SaveChanges();

No comments:

Post a Comment