I want to check if user exists in database by username with SQL query using ADO.NET in ASP.NET WebAPI.
Like in Entity there is Any() call that does job.
private async Task<bool> UserExists(string username)
{
return await context.Contacts.AnyAsync(x => x.UserId == username.ToLower());
}
if (await UserExists(createUserDto.Username))
return BadRequest("Username is taken");
I want to do the same job but manually with SQL query and to store that object in var user and finally ask if there is a user in DB...(and to do other coding with that user).
I am passing CreateUserDtO which I want to create, to function with property string userId further in the body of getUserByUserName. UserId is string.
var user = await accountRepository.GetUserById(createUserDto.UserId);
I am opening connection, executing query, commit/rollback transaction and closing connection in GetUserById(string username). I just want to know how my query should be look like that returns object of that user.
public Task<bool> GetUserById(string username)
{
int result = 0;
bool success = false;
string usernameCheck = username.ToLower();
try
{
OpenConnection();
BeginTransaction();
string query = "...";
SqlCommand command = new SqlCommand(query, connection, transaction);
result = "..."
}
catch (Exception ex)
{
_ = log.WriteLine("ERROR : " + ex.Message + "\nStackTrace : " + ex.StackTrace);
}
finally
{
if (result == 1)
{
CommitTransaction();
success = true;
}
else
{
RollbackTransaction();
}
CloseConnection();
}
return success;
}
}
Is that possible?