Home > Enterprise >  Find record based on value from the table
Find record based on value from the table

Time:07-31

This is my code to find string in my UserTable.

var PhoneExists = _db.UserTable.Where(u => u.PhoneNumber == Input.PhoneNumber);

and this is my if code:

if (PhoneExists != null)
{
    ErrorAlert("number found.");
    return Page();
}

but every time the if condition is true.

CodePudding user response:

It returns true as PhoneExists is not null, but it returns with IQueryable value.

You need to materialize the query to return the result queried from the database.

You may look for .Any() to find whether there is any record with the respective PhoneNumber existed.

bool PhoneExists = _db.UserTable.Any(u => u.PhoneNumber == Input.PhoneNumber);

if (PhoneExists)
{
    ...
}

CodePudding user response:

Where will always return a non-null enumerable, and it's empty if there are no matches. You have to check its contents. If you expect the phone numbers to be unique, you could use FirstOrDefault or SingleOrDefault to return either a string, or null. The latter will, however, throw if there is more than one match.

CodePudding user response:

You can use Contains here.

Sample code:

var PhoneExists = _db.UserTable.Where(u => u.PhoneNumber.Contains(Input.PhoneNumber)).FirstOrDefault();

In your if code:

if (PhoneExists != null && PhoneExist.Count()== 0)
{
 ErrorAlert("number found.");
 return Page();
}

CodePudding user response:

You can use Exists instead of Where like this :

if (_db.UserTable.Exists(u => u.PhoneNumber == Input.PhoneNumber))
{
    //Do Something
}

About exist checkout https://docs.microsoft.com/tr-tr/dotnet/api/system.collections.generic.list-1.exists?view=net-6.0

  • Related