0
I am trying to make a Generic method for return of Procedure, but when picking up Datarow to make a Cast generates the following error:
Unable to cast Object of type 'System.Data.Datarow' to type 'Classeparagerar'.
I am 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 make 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;
}
yes, how will the cast know which column to map to which class property? this has to be done manually. Also consider using a framework to help, such as Automapper for example, there are several that can help simplify
– Ricardo Pontual
An unnecessary code for this context, which can lead to poor performance by the structures used ... !!!
– novic
Ricardo Punctual do you know the Explicit or the implicit Operator? When you need to do some validation of this type, you can use a type conversion operator, in this case I want to use this operator and this is where the error occurs.
– José Leal Marques
The cast will only be automatic if the return of the Procedure matches the columns, types and order with the class attributes
– Leandro Angelo