Ayorus
Ayorus

Reputation: 507

How to update a field using its own value with only one query?

Considering the folling query:

UPDATE t1 SET p1 = p1 + 10 WHERE id = @id

How can I achieve the same behaviour in EntityFramework with only one query?

Currently, I am doing is this:

    var obj = BD.Objs.Single<objclass>(x=> x.id == id);
    obj.p1 = obj.p1 + 10;
    BD.SaveChanges();

But this wastes a DB access querying the object

Upvotes: 1

Views: 56

Answers (2)

Ayorus
Ayorus

Reputation: 507

I decided to manually build the query and execute it. Something like this:

string Sql = string.Format(" UPDATE t1 SET p1 = p1 + {0} WHERE ID = {1}; ", 10,1);
Bd.Database.ExecuteSqlCommand(Sql);

Upvotes: 0

ocuenca
ocuenca

Reputation: 39346

Well, there is a way to do it, but you will need to use an 3rd party library (Entity Framework Extended Library)

context.Objs
    .Where(t => t.id== id)
    .Update(t => new Obj{ p1= t.p1+10 });

This is the nuget package you will need to install. This library eliminates the need to retrieve and load an entity before modifying it. You can use it as well for delete or update entities.

Upvotes: 1

Related Questions