Dave S
Dave S

Reputation: 1423

Increment an integer in a Simple.Data Update query

Is it possible to increment an integer in an Update query using Simple.Data?

My database is SQL Server, but I know Simple.Data is designed to be database agnostic so perhaps this query is not available in other providers.

The SQl query I am trying to generate would look like this:

UPDATE MyTable SET MyInt = MyInt + 1 WHERE Id = 123

Currently I have to do a SELECT and an UPDATE in Simple.Data to achieve the same thing:

var result = db.MyTable.Find(db.MyTable.Id == 123);
result.MyInt++;
db.MyTable.UpdateById(Id: result.Id, MyInt: result.MyInt );

I am wondering if there is a way to replicate the single SQL statement above.

Upvotes: 0

Views: 207

Answers (2)

Norbert Norbertson
Norbert Norbertson

Reputation: 2220

I have found this does not work if the int is nullable and the current value is null. Nothing happens. But if I set the value to 0 then it works. So my int col now has a default of 0.

Upvotes: 0

Mark Rendle
Mark Rendle

Reputation: 9414

You can do this:

db.MyTable.UpdateById(Id: 123, MyInt: db.MyTable.MyInt + 1);

Works on SQL Server, should work in all the SQL-based providers.

Upvotes: 1

Related Questions