Reputation: 377
I have this linq query:
string appuserid = (from c in db.AppUsers
where (c.AppUserID == AppUserId)
select c.AppUserID).Single().ToString();
Lets say testuser1 does not exist in the db
If I let AppUserId = testuser1
I get:
System.InvalidOperationException.
My question is, is there anyway to rewrite this query to avoid this error and perhaps return an empty string or let it be null? I need to return something that I can write some logic around.
Upvotes: 0
Views: 2900
Reputation: 266
string appuserid = (from c in db.AppUsers
where (c.AppUserID == AppUserId)
select c.AppUserID).SingleOrDefault() ?? String.Empty;
This will return an empty string.
Upvotes: 2
Reputation: 53958
You could use the method SingleOrDefault
. Then you could check if that you get is not or not.
var appUser = (from c in db.AppUsers
where c.AppUserID == AppUserId
select c).SingleOrDefault();
if(appUser!=null)
var appUserId = appUser.AppUserID.ToString();
Or more compact:
var appUser = db.AppUsers.SingleOrDefault(x=>x.AppUserID==AppUserId);
if(appUser!=null)
var appUserId = appUser.AppUserID.ToString();
The method SingleOrDefault
returns the single item from a sequence for which the predicate (the expression in the where clause) is true. If there are more than one items, for which the predicate is true, an exception will be thrown. Furthermore, if there isn't any item in the sequence for which the predicate is true, you will get the default value for the projected item.
Upvotes: 1
Reputation: 12874
Try this
string appuserid = (from c in db.AppUsers
where (c.AppUserID == AppUserId)
select c.AppUserID).SingleOrDefault();
This will return null, if no element found.
Upvotes: 1