This string is called Linq. Is there a more efficient approach to compare in the query?

entity-framework linq

Question

Originally I had this method:

public virtual User GetUser(string username)
        {
            return _db.Users.Single(x => x.UserName == username);
        }

So basically a linq method which gets a user based on the person's username.

Trouble was I found that sometimes the username was coming through with an uppercase character at the start so it wasn't always working.

So then I came up with:

public virtual User GetUser(string username)
        {
            return _db.Users.Single(x => (string.Compare(x.UserName, username, true) == 0));
        }

This works. However I get this must be really inefficient to do a string.Compare for the users?

Is there a better way to write this without the string.Compare?

1
2
4/18/2012 4:23:03 AM

Accepted Answer

public virtual User GetUser(string username)
        {
            return _db.Users.Single(x => x.UserName.ToLower() == username.ToLower());

        }

But I don't think the compare will be much slower though....

1
4/18/2012 4:29:39 AM

Popular Answer

String.Compare is not in the list of functions supported by entity framework (see Supported Function List) This means that when you perform this query entity framework will retrieve the whole data set required to execute this compare and perform the compare locally. This will be very slow.

A much better solution is to use == to compare strings, for example:

return _db.Users.Single(x => x.UserName == username);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow