I have a Payment model with a 'Status' boolean value which defaults to false. Once payment has been made, I need to update that specific payment's 'Status' to true.
Here's the code I've been trying to use to change the specific database entry, but it's just not changing it. What am I doing wrong?
Payment payment = new Payment();
payment = db.Payments.Find(orderId);
db.Entry(payment).State = EntityState.Modified;
payment.Status = true;
db.SaveChanges();
Thanks!
This is what ended up working:
using (var con = new ApplicationDbContext())
{
payment = con.Payments.First(x => x.Id == orderId);
payment.Status = true;
con.Payments.Attach(payment);
var entry = con.Entry(payment);
entry.Property(e => e.Status).IsModified = true;
con.SaveChanges();
}
Payment payment = new Payment();
payment = db.Payments.Find(orderId);
payment.Status = true;
db.Entry(payment).State = EntityState.Modified;
db.SaveChanges();
The reason all of these are failing is because either the Payment object is never attached to the DBContext or the orderId doesn't actually match up with the PK on the Payments table. In order for SaveChanges()
to actually work, the object you're changing needs to be tracked by the DBContext, not just have its EntityState
set to Modified
. Also all these examples seem grossly overcomplicated.
using (var db = new DbContext())
{
// make sure you have the right column/variable used here
var payment = db.Payments.FirstOrDefault(x => x.Id == orderId);
if(payment == null) throw new Exception("Invalid id: " + orderId);
// this variable is tracked by the db context
payment.Status = true;
db.SaveChanges();
}