I have a field where i'm counting the total number of subscriptions to an user. Right now i update this field like this:
using (var context = new AppDbContext())
{
var foundEntry = context.Users.Find(id);
if (foundEntry != null)
{
foundEntry.TotalSubscriptions = foundEntry.TotalSubscriptions + 1;
context.Entry(foundEntry).CurrentValues.SetValues(foundEntry);
var result = context.SaveChanges();
}
}
But this way i have to make 2 queries to the db. One to get the current total count and one to update the value.
Is there a way to do this with only one query to the db with entity framework?
I wanted to try something like this:
var user = new User() { Id = userId, TotalSubscriptions = currentS + 1 };
db.Users.Attach(user);
db.Entry(user).Property(x => x.TotalSubscriptions).IsModified = true;
but the problem i'm facing is that i would have to get the current count first but don't know how to do in in a single query. I think that 1 query for this is possible with a raw SQL statement/query.
I'm trying to archive something like this: https://stackoverflow.com/a/2762856/1286942 but with entity framework.
UPDATE
I also tried something like this:
var user = new User() { Id = userId };
db.Users.Attach(user);
user.TotalSubscriptions = context.Entry(user)
.Property(u => u.TotalSubscriptions).OriginalValue + 1;
db.Entry(user).Property(x => x.TotalSubscriptions).IsModified = true;
But the problem is that the .OriginalValue
and the .OriginalValue
always return 0. So the TotalSubscriptions
field is always updated to -1 or 1.
UPDATE #2
Right now i see only this as an option:
var numberOfUpdatedRows = context.Database
.ExecuteSqlCommand("UPDATE dbo.Users
SET TotalSubscriptions = TotalSubscriptions + 1
WHERE id = " + id + "");