1

I'm using EF, but can't add 1 to property counted (column in SQL)

How to add counted+1 in Entity Framework?

Like in

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();

How to do that?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user4144972
  • 47
  • 1
  • 10

1 Answers1

0

You need to use something like this:

  • retrieve the entity with ID=2
  • add 1 to the property
  • save the modified entity back

In code:

// 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();
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I know, but then EF will call the database twice. Isn't any way to update without retrieve the entity with id =2 ? – user4144972 Mar 10 '15 at 19:12
  • @user4144972: you can always just **execute** plain SQL ..... but that kinda defeats the **whole point** of using EF .... – marc_s Mar 10 '15 at 19:13
  • I have thinked about to do it, but the rest of the is EF, I cant be the first with problem – user4144972 Mar 10 '15 at 19:17
  • See [this other SO question](http://stackoverflow.com/questions/12751258/batch-update-delete-ef5) about certain add-ons to allow you to do batch operations in EF – marc_s Mar 10 '15 at 19:24
  • I choosed to use plain SQL this time – user4144972 Mar 10 '15 at 21:08