Refactoring some C# code and I am trying to create a new update method. It is working successfully but its not actually updating. This is my first time doing this in C# so I have been working off a few blogs and I can’t tell whats different from what I saw on there. Here are the 2 solutions I tried:
public async Task<BillableDto> PutBillable(Guid Id, BillableDto billable)
{
var view = await _context.Billables
.Where(b => b.Id == Id)
.SingleOrDefaultAsync();
if (view == null)
throw new NotFoundException("BillableNotFound");
view.Id = billable.Id;
view.Name = billable.Name;
view.Cost = billable.Cost;
view.Type = billable.Type;
view.PunchId = billable.PunchId;
view.Punches = billable.Punches;
_context.Update(view);
return new BillableDto
{
Id = view.Id,
Name = view.Name,
Cost = view.Cost,
Type = view.Type,
PunchId = view.PunchId,
Punches = view.Punches
};
}
Attempt #2:
public async Task<bool> PutBillable(Guid Id, BillableDto billable)
{
var view = await _context.Billables
.Where(b => b.Id == Id)
.SingleOrDefaultAsync();
if (view == null)
throw new NotFoundException("BillableNotFound");
view.Id = billable.Id;
view.Name = billable.Name;
view.Cost = billable.Cost;
view.Type = billable.Type;
view.PunchId = billable.PunchId;
view.Punches = billable.Punches;
_context.Update(view);
return true
}
Any tips on these here?
>Solution :
Not entirely clear what database and database access layer you’re using – assuming it’s some kind of Entity Framework – then you’re most likely misunderstanding the Update method on the context.
Here’s what the official MS docs says:
Begins tracking the given entity and entries reachable from the given entity using the Modified state by default, but see below for cases when a different state will be used.
Most importantly: it does NOT actually apply any update back to the database – for that, you’d need to call
await _context.SaveChangesAsync();
Also: since you’re loading the view from the context, and then making changes to it – you don’t even need to call .Update at all… the view will already be marked as "Modified" by the EF change tracker.
So try something like this:
public async Task<bool> PutBillable(Guid Id, BillableDto billable)
{
var view = await _context.Billables
.Where(b => b.Id == Id)
.SingleOrDefaultAsync();
if (view == null)
throw new NotFoundException("BillableNotFound");
view.Id = billable.Id;
view.Name = billable.Name;
view.Cost = billable.Cost;
view.Type = billable.Type;
view.PunchId = billable.PunchId;
view.Punches = billable.Punches;
await _context.SaveChangesAsync();
return true;
}