C
C#3y ago
kopuo

❔ 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
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
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?
2 Replies
Angius
Angius3y ago
Well, yeah After .Select() it's a different object What if you .Select(p => p.Price)? Or .Select(p => new { Cost = p.Price, Text = p.Name }? EF has no way to track those If you want to edit the entity, you need it whole Or you can use .ExecuteUpdateAsync() that was added in EF Core 7 .Select() is used when you only intend to display the values, not change them
Accord
Accord3y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server