Hugo Rocha
Hugo Rocha

Reputation: 537

Entity Framework - Update/add value to existing value

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.

Upvotes: 1

Views: 1632

Answers (2)

Alexei - check Codidact
Alexei - check Codidact

Reputation: 23108

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

Upvotes: 1

Mike
Mike

Reputation: 4051

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

Upvotes: 2

Related Questions