I have a pretty simple helper method to generate a unique code. To ensure that codes are unique I execute a LINQ to Entities query to verify that it isn’t already in use.
My first attempt at writing this method worked perfectly:
public string GenerateUniqueSignUpCode()
{
while( true )
{
var code = Path.GetRandomFileName().Substring( 0, 6 ).ToUpper();
if( !Context.Users.Any(e => e.SignUpCode.ToUpper() == code) )
return code;
}
}
However, R# suggested that the LINQ expression could be simplified, which resulted in this method:
public string GenerateUniqueSignUpCode()
{
while( true )
{
var code = Path.GetRandomFileName().Substring( 0, 6 ).ToUpper();
if( Context.Users.All(e => e.SignUpCode.ToUpper() != code) )
return code;
}
}
This rewrite causes an infinite loop. The database does not contain any 6-character codes when the code is run so it should exit the loop on the first attempt (as does the first method shown).
Is All broken in EF 4.3.1 or what’s going on?
My guess is that this will happen if
SignupCodeis null for any entry. The comparison using!=won’t give a “true” result, soAllwill return false.Just a guess, but it’s the kind of thing I’ve seen before. You could try: