C
C#2y ago
Natty

Updating a property and saving it to DB (EF Core)

I have a List of objects that I queried from my db context. I’m trying to change one property on it, such as: responses.ForEach(r => r.Status = “Done”); Then I’m calling _db.SaveChanges(); I’m not seeing the status updated in the database, am I doing something wrong?
11 Replies
Natty
NattyOP2y ago
I think I’m only updating the list of responses, locally, and not actually the value that’s in the DB? (Sorry for format, can’t open discord on work laptop)
Saber
Saber2y ago
I'm assuming responses here would be the entities retrieved from the db context?
Natty
NattyOP2y ago
Yes var responses = _db.ResponseStage.Where(x => x.Status == “Start”).ToList();
Saber
Saber2y ago
is tracking disabled by default?
Natty
NattyOP2y ago
Hm I’m not sure/familiar, it shouldn’t be… let me see if I can find out. I don’t think so… not seeing anything.
Angius
Angius2y ago
First thing's first, I'd use a normal loop instead of .ForEach() Unlikely it's what causes issues, but better safe than sorry
Natty
NattyOP2y ago
If this code looks like it should work, then it’s possible I’m just not using MS SQL Server correctly. Just wanted to ensure the code is correct.
Angius
Angius2y ago
MSSQL or not, it should work
Natty
NattyOP2y ago
I mean for checking the db values, which im using MSSQL to do so. Just not seeing the changes in there. Sounds good re the code then, must be an issue elsewhere.
Angius
Angius2y ago
var things = await _context.Things
.Where(t => t.Status = Status.Start)
.ToListAsync();

foreach (var t in things)
{
t.Status = Status.Done;
}

await _context.SaveChangesAsync();
var things = await _context.Things
.Where(t => t.Status = Status.Start)
.ToListAsync();

foreach (var t in things)
{
t.Status = Status.Done;
}

await _context.SaveChangesAsync();
That's how I'd write it, and your code is pretty much the same So it should work Well, the same sans async
Natty
NattyOP2y ago
Yup that’s what I had changed too as well, all good. Thank you!
Want results from more Discord servers?
Add your server