I have a very specific LINQ query. I would like to check for a randomly generated key in the table.
A standard query can be defined as Select * from Products where SaleId == 'XXXXXXX'. In this request, XXXXXX is generated by a random character generator (length is also provided). I created the following LINQ extension:
public static string GetUniqueId<T, TProperty>(this IEnumerable<T> source, int length, Func<T, TProperty> idProperty)
{
bool isUnique = false;
string uniqueId = String.Empty;
while (!isUnique)
{
uniqueId = PasswordGenerator.GenerateNoSpecialCharacters(length);
if (!String.IsNullOrEmpty(uniqueId))
{
isUnique = source.AsQueryable().SingleOrDefault(i => idProperty(i).Equals(uniqueId)) == null;
}
}
return uniqueId;
}
However, I noticed that this method first selects all the records from the table, which is passed as the source, and then runs the Where clause. This behavior obviously takes a lot of time. So basically this SELECT * FROM Productsand then runs SingleOrDefault
Is there a way that I could directly run the query so that it selects * from the products WHERE Id = 'XXXXXXX'
Here is an example of what I call it:
string id = c.L2SOnlineCountMasters.GetUniqueId(9, x => x.MID);
L2SOnlineCountMasters c DataContext.
!
Cheerz,
Anup