我使用EF,但无法在属性counted
中添加1(SQL中的列)
如何在实体框架中添加count + 1?
喜欢
SQL
update cars
set counted = counted + 1
where id = 2
EF
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();
怎么做?
答案 0 :(得分:0)
您需要使用以下内容:
在代码中:
// 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();
}
}