我正在使用 EF,但无法将 1 添加到属性counted
(SQL 中的列)
如何在实体框架中添加计数+1?
喜欢在
.SQL
update cars
set counted = counted + 1
where id = 2
英 孚
var cars= new Cars();
cars.Id= 2;
db.Cars.Attach(cars);
var entry = db.Entry(cars);
entry.Property(e => e.counted).IsModified = true;
db.SaveChanges();
怎么做?
你需要使用这样的东西:
- 检索 ID=2 的实体
- 向属性添加 1
- 保存修改后的实体
在代码中:
// create context to use
using (YourDbContext ctx = new YourDbContext())
{
// try to find car with Id = 2
var carId2 = ctx.Cars.FirstOrDefault(c => c.Id == 2);
// if found .....
if (carId2 != null)
{
// .... update the Counted property by one
carId2.Counted = carId2.Counted + 1;
// save those changes back to the database
ctx.SaveChanges();
}
}