1

In Entity Framework is it possible to add a value to existing value in the database? Currently I have this:

var ent = this.repository.GetSingle(id);
var moreQuantity = 5; // This is calculated in application logic
ent.quantity = ent.quantity + moreQuantity;
this.repository.SaveChanges();

It is possible to do the same in a single database interaction? I mean something like this in SQL:

UPDATE table SET quantity = quantity + {moreQuantity} WHERE id = {id}

Without using ExecuteSqlCommand or ExecuteStoreQuery.

The reason I am asking this is because there is a significant amount of time between the GetSingle and SaveChanges in my application, so I run with some concurrency problems. I manage to solve it with RowVersion and ConcurrencyCheck but I was looking for a better implementation.

Thanks in advance.

2
  • which version of EF are you using? Commented Dec 7, 2015 at 14:22
  • @MikeMazmanyan Hi, 6.1.1 Commented Dec 7, 2015 at 14:25

2 Answers 2

2

There is a nice library EntityFramework.Extended

Install it and write:

context.repository.Update(e => e.id == id, e2 => new entity { quantity = e2.quantity + moreQuantity });

Sign up to request clarification or add additional context in comments.

Comments

1

Current version of EntityFramework Extended (6.1) has deprecated the overload indicated in the accepted answer. The filtering and the actual update should be separated now. This is a good thing, since filtering can be easily dynamically constructed.

For the actual question, the query should like the following:

context.repository
    .Where(e => e.id == id)
    .Update(e2 => new entity { quantity = e2.quantity + moreQuantity });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.