A
A
Andrew2016-03-19 03:04:05
.NET
Andrew, 2016-03-19 03:04:05

Why is it not saved to the database?

There is such a code

var user = await db.Users.FindAsync(id);
user.Age = 20;

var someRes = user.Table1.Table2.SelectMany(
    s =>//тут критерии выбора
).ToList();

for (int i = 0; i < someRes.Count; i++)
{
    var r = someRes [i];
    r.DateTime = DateTime.UtcNow;
}

await db.SaveChangesAsync();

the field with Age changes. In someRes, the correct selection is obtained, and during debugging, when the loop passes, it is clear that the DateTime fields inside it change. But when saving, the field values ​​are not saved, the old values ​​remain.
Where am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2016-03-19
@byte916

You forgot to call Update on every element that has changed.
More or less like this
db.Users.Update(user);

R
Roman, 2016-03-20
@yarosroman

No need to do ToList(), this method makes a new list, while changes in entities are not tracked by EF.

var result = context.Users.Include(...).Where(...);
foreach(User u in result)
{
     u.Name="Domain\\"+Name;
}
await context.SaveChangesAsync();

ToList() is best used if you need to cache a sequence, for example if you need to iterate through a collection and remove some data, foreach will throw an exception that the sequence has changed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question