0

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.

user2133925
  • 377
  • 2
  • 4
  • 15

3 Answers3

2
string appuserid = (from c in db.AppUsers
                          where (c.AppUserID == AppUserId)
                          select c.AppUserID).SingleOrDefault() ?? String.Empty;

This will return an empty string.

kirkmcpherson
  • 266
  • 1
  • 4
  • 9
1

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.

Kishore Kumar
  • 12,675
  • 27
  • 97
  • 154
1

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.

Christos
  • 53,228
  • 8
  • 76
  • 108