rp.
rp.

Reputation: 17683

Performing an update with LINQ

I am digging into LINQ--trying to understand basic models (it seems pretty cool to me). The code below is the code to perform before committing an update.

   Linq01.Account acc = context.Accounts.Single( pc => pc.AccountID == AccountID );
   acc.Name = textboxAccountNameRead.Text.Trim();
   context.SubmitChanges();

So far, so good. But what do you do if the Single() method failed--if the account ID wasn't found?

Thank you!

Upvotes: 2

Views: 316

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503489

To add to Slace's answer, if you call Single and then account ID wasn't found, it will throw an exception. In some cases that's more appropriate than returning null and explicitly handling it.

Upvotes: 1

Aaron Powell
Aaron Powell

Reputation: 25117

You should use SingleOrDefault, if the query does not return a value you can check it against null:

var acc = context.Accounts.SingleOrDefault(pc => pc.AccountId == AccountId);
if(acc != null)
{
  acc.Name = textboxAccountNameRead.Text.Trim();
  context.SubmitChanges();
}

Upvotes: 9

Related Questions