JasonMcF

In my application I want to check if a record exists, if it does I want to update it, if it does not then I want to create a new record.

Originally I just used the Single operator as follows:

ADMUser admUser = myDBContext.ADMUser.Single<ADMUser>(c => c.ADMUserId == userId);

if (admUser != null) {

admUser.LastRegistered = DateTime.Now;

} else {

admUser = new ADMUser();

:

:

myDBContext.ADMUser.Add(admUser);

}

The first line of code caused an exception when there was no record matching which I discovered later, after reading the manual!, is correct functionality for the Single operator.

I now use the Count operator instead with the following code:

ADMUser admUser;

int usrCount = myDBContext.ADMUser.Count<ADMUser>(c => c.ADMUserId == userId);

if (usrCount > 0) {

admUser = myDBContext.ADMUser.Single<ADMUser>(c => c.ADMUserId == userId);

admUser.LastRegistered = DateTime.Now;

} else {

admUser = new ADMUser();

:

:

myDBContext.ADMUser.Add(admUser);

}

This second code segment works as expected. Is this the best way to do what I want to achieve or is there a more efficient way

Cheers,

Jason



Re: LINQ Project General Use of Single() method

Fabrice MARGUERIE

I think SingleOrDefault is what you are looking for. It will return null if no element can be found.