将1添加到属性实体框架

时间:2015-03-10 19:02:02

标签: entity-framework

我使用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();

怎么做?

1 个答案:

答案 0 :(得分:0)

您需要使用以下内容:

  • 检索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();
    }
}