I have this issue that is eating my mind. The thing is that the _reader is not reading anything.
I have this code:
public DataEntities.Usuario GetUser(string field, string value)
{
using (SqlConnection connection = new SqlConnection(@"connectionstring"))
{
using (SqlCommand query = new SqlCommand())
{
DataEntities.Usuario _usuario = new DataEntities.Usuario();
if (field == "id" || field == "username" || field == "emailaddress")
{
query.Connection = connection;
query.CommandType = CommandType.StoredProcedure;
query.CommandText = "GetUser";
var pField = query.Parameters.AddWithValue("@Field", field);
pField.Direction = ParameterDirection.Input;
var pValue = query.Parameters.AddWithValue("@Value", value);
pValue.Direction = ParameterDirection.Input;
try
{
connection.Open();
SqlDataReader _reader = query.ExecuteReader();
>>> while(_reader.Read())
{
_usuario.EmailAddress = (string)_reader["EmailAddress"];
_usuario.Username = (string)_reader["Username"];
_usuario.FirstName = (_reader["FirstName"] != DBNull.Value) ? (string)_reader["FirstName"] : string.Empty;
_usuario.LastName = (_reader["LastName"] != DBNull.Value) ? (string)_reader["LastName"] : string.Empty;
_usuario.MobileNumber = (_reader["MobileNumber"] != DBNull.Value) ? (string)_reader["MobileNumber"] : string.Empty;
}
_reader.Close();
return _usuario;
}
catch (SqlException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
finally
{
connection.Close();
}
}
return _usuario;
}
}
}
And I have this Stored Procedure:
CREATE PROCEDURE [dbo].[GetUser]
@Field nvarchar(100),
@Value nvarchar(100)
AS
SELECT EmailAddress,
Username,
FirstName,
LastName,
MobileNumber,
Register_Date
FROM Users
WHERE @Field = @Value
RETURN 0
And this is not returning anything. This doesn't generate an exception but when it arrives to the while loop it jumps and end it returning the created object with everything null.
Any clues? I've tried to change the STORED PROCEDURE but without luck,