C#
C#

help

Root Question Message

kopuo
kopuo11/10/2022
❔ EntityFramework does not track changes for the select projection

Hey, With Select (), I only extracted the data I needed, which I want to update later. However, after SaveChanges () is executed, the value in DB does not change.

var product = await _dbContext.Products
                .Include(x => x.Additionals)
                .Where(p => p.Id == Id)
                .Select(x => new Product { Id = x.Id, Name = x.Name, Additionals = x.Additionals })
                .SingleOrDefaultAsync();

product.Name = "ChangedName";
await _dbContext.SaveChangesAsync();   //no database changes


On the other hand, with such a code, the change already appears correctly

var product = await _dbContext.Products
                .Include(x => x.Additionals).SingleOrDefaultAsync(p => p.Id == Id);

product.Name = "ChangedName";
await _dbContext.SaveChangesAsync();   //correct changes


Can I somehow make changes to the truncated retrieved data like in the first code?
Angius
Angius11/10/2022
Well, yeah
Angius
Angius11/10/2022
After .Select() it's a different object
Angius
Angius11/10/2022
What if you .Select(p => p.Price)?
Angius
Angius11/10/2022
Or .Select(p => new { Cost = p.Price, Text = p.Name }?
Angius
Angius11/10/2022
EF has no way to track those
Angius
Angius11/10/2022
If you want to edit the entity, you need it whole
Angius
Angius11/10/2022
Or you can use .ExecuteUpdateAsync() that was added in EF Core 7
Angius
Angius11/10/2022
.Select() is used when you only intend to display the values, not change them
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy