Pergunta

I need to update all rows of my table when user visits one specific page. All fields need to be updated to "false". I tried this code:

var history = db.UserHistory.Where(m => m.UserID == id);
TryUpdateModel(history);
history.IsActive = false;
db.SaveChanges();

But it throws me an error message. Anyone could help me with this update?

Foi útil?

Solução

I couldn't get at first that LINQ didn`t update many rows at once, I have to make a loop and update each one. My final code is this one:

var history = db.UserHistory.Where(m => m.UserID == id).ToList();
TryUpdateModel(history);
history.ForEach(m => m.IsActive = false);
db.SaveChanges();

Outras dicas

Since it seems like you're just selecting a single entry you want to probably want to append .FirstOrDefault() to your first line, which should appear with intellisense.

var history = db.UserHistory.Where(m => m.UserID == id).FirstOrDefault();
TryUpdateModel(history);
history.IsActive = false;
db.SaveChanges();

Right now you're returning an IQueryable as opposed to a single entry. FirstOrDefault will return a single UserHistory entity, so at least you'd be passing a single item to TryUpdateModel.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top