我有一个支付模型,其'状态'布尔值默认为false。付款完成后,我需要将特定付款的“状态”更新为true。
这是我一直试图用来更改特定数据库条目的代码,但它只是没有改变它。我做错了什么?
Payment payment = new Payment();
payment = db.Payments.Find(orderId);
db.Entry(payment).State = EntityState.Modified;
payment.Status = true;
db.SaveChanges();
谢谢!
这就是最终的工作:
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();
}
答案 0 :(得分:10)
Payment payment = new Payment();
payment = db.Payments.Find(orderId);
payment.Status = true;
db.Entry(payment).State = EntityState.Modified;
db.SaveChanges();
答案 1 :(得分:3)
所有这些都失败的原因是因为Payment对象永远不会附加到DBContext,或者orderId实际上与Payments表上的PK不匹配。为了使SaveChanges()
能够真正发挥作用,您需要通过DBContext跟踪您正在更改的对象,而不是将其EntityState
设置为Modified
。所有这些例子似乎都非常复杂。
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();
}
答案 2 :(得分:1)
试试这个:
Payment payment;
using (var context = new DBContext()) //replace the name of your context
{
payment = context.Payments.Find(orderId);
}
if(payment != null)
{
payment.Status = true;
}
using (var context = new DBContext()) //replace the name of your context
{
context.Payments.Attach(payment);
context.Entry(payment).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
答案 3 :(得分:1)
如上所述here:
DbSet上的Find方法使用主键值来尝试查找上下文跟踪的实体。如果在上下文中找不到该实体,则将向数据库发送查询以在那里找到该实体。如果在上下文或数据库中找不到实体,则返回Null。
所以请确保Payment类看起来像这样:
public class Payment
{
[Key]
public int Id {get; set;}
public bool Status {get; set;}
}
您的Entry保存逻辑可能如下所示:
Payment payment = null;
using (var ts = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(1, 0, 0, 0)))
{
using (var context = new DBContext())
{
context.Database.Log = s => { System.Diagnostics.Debug.WriteLine(s); };
payment = context.Payments.Find(orderId);
if(payment != null)
{
payment.Status = true;
context.Entry(payment).State = System.Data.EntityState.Modified;
}
else
{
context.Payments.Add(new Payment(){
Status = true
});
}
context.SaveChanges();
}
ts.Complete();
}
添加了事务范围以确保它正确打开和关闭,并将sql查询日志记录添加到调试窗口。