2

In my database, I have a single item that I want to update. I tried doing something like this, but it doesn't work:

db.Items.Where(t => t.Id == itemId).Select(t =>
            {
                t.CurrentValue = 99;
                t.TotalValue = 999;
            });

What works is this code, but I think that this is inefficient (am I wrong?):

db.Items.Single(t => t.Id == itemId).TotalValue = 999;
db.Items.Single(t => t.Id == itemId).CurrentValue = 99;
db.SaveChanges();

Is there a way to update different properties of a single object, with a single query?

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
ojek
  • 9,680
  • 21
  • 71
  • 110

1 Answers1

3

You are correct, running db.Items.Single(...) multiple times may be suboptimal.

Calling it once and then referencing its properties should be more efficient:

var item = db.Items.Single(t => t.Id == itemId);
item.TotalValue = 999;
item.CurrentValue = 99;
db.SaveChanges();
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Oh. This works perfectly. Thank you. Now i wonder, how does it know how to connect item object with db object? I didn't specify it anywhere. – ojek Aug 15 '12 at 13:27