tags:

views:

208

answers:

2

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!

+9  A: 

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();
}
Slace
Damn. I just did that with a select operation this morning. Thank you very much.
rp
A: 

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.

Jon Skeet