I'm trying to do a Generic method for procedure return, but getting DataRow to do a Cast generates the following error:
Unable to cast object of type 'System.Data.DataRow' to type 'ClassGreen'.
I'm using a Conversion Type Operator
public class Pesquisa
{
public string NOME { get; set; }
public string IDADE { get; set; }
public static explicit operator Pesquisa(DataRow model)
{
if (model == null)
return null;
var result = new Pesquisa();
try
{
if(model["NOME"] != null)
result.NOME = model["NOME"].ToString();
if (model["IDADE"] != null)
result.IDADE = model["IDADE"].ToString();
}
catch (Exception ex)
{
}
return result;
}
}
How can I do this automatic conversion?
public List<TEntity> ExecuteCommandGeneric<TEntity>(string procName, SqlParameter[] Parametros, CommandType commandType)
{
DataTable dt = new DataTable();
try
{
using (SqlConnection connection = new SqlConnection(StrConnecting))
{
using (SqlCommand command = new SqlCommand { Connection = connection, CommandText = procName, CommandType = commandType })
{
SqlDataAdapter adapter = new SqlDataAdapter(command);
if (!(Parametros == null))
{
for (int i = 0; (i <= (Parametros.Length - 1)); i++)
{
if (Parametros[i].Value != null)
if (!VerificaSeguranca(Parametros[i].Value.ToString()))
throw new Exception("Erro 171 - Contate o Suporte!");
command.Parameters.Add(Parametros[i]);
}
}
connection.Open();
adapter = new SqlDataAdapter(command);
adapter.TableMappings.Add("Table", procName);
adapter.Fill(dt);
}
connection.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
List<TEntity> listGeneric= dt.Rows.Cast<TEntity>().ToList();
return listGeneric;
}