2
I’m new to the forum and I’d like some help. I am trying to pass a junction of tables with client information to C# but am having problems turning 1xN fields into objects. I want to bring the fields ID, Name, Sex, Area Code and Phone; Since the customer can have more than one phone. My problem is that when you make this select of that Join on SQL server and a client has more than one phone, the table will repeat all fields and change only the DDD and phone. When I turn the data from the table I took from the database into a list, the list is identical to Join done on Windows server. I’d like to know how I can turn this second DDD and phone into another object. Connection Class with BD:
public class AccessBd
{
private SqlConnection CreateConnextion()
{
return new SqlConnection(@"Data Source=DESKTOP-T1LNBJO\SQLEXPRESS;Initial Catalog=TESTEOFICINA;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
}
//Parametros que irão para o banco
private SqlParameterCollection sqlParameterCollection = new SqlCommand().Parameters;
public void ParameterCleaner()
{
sqlParameterCollection.Clear();
}
public void AddParameters(string parameterName, object parameterValue)
{
sqlParameterCollection.Add(new SqlParameter(parameterName, parameterValue));
}
public DataTable ExecuteSelect(CommandType commandType, string spOrText)
{
try
{
//Criar a conexão
SqlConnection sqlConnection = CreateConnextion();
//Abrir Conexão
sqlConnection.Open();
//Criar Comando que leva informação para o banco
SqlCommand sqlCommand = sqlConnection.CreateCommand();
//Colocando as coisas dentro do comando
sqlCommand.CommandType = commandType;
sqlCommand.CommandText = spOrText;
//Tempo máximo que o programa pode tentar executar o comando sql
sqlCommand.CommandTimeout = 50;
//Adicionar os parametros no comando
foreach (SqlParameter sqlParameter in sqlParameterCollection)
{
sqlCommand.Parameters.Add(new SqlParameter(sqlParameter.ParameterName, sqlParameter.Value));
}
//Criando um adaptador
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
//DataTable -> Tabela de dados Vazia onde vou colocar os dados que vem do banco
DataTable dataTable = new DataTable();
//Mandar o comando ir até o banco buscar os dados e preencher o datatable
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
Class that takes data from BD:
public class BusinessClients
{
List<Clients> clientCollection = new List<Clients>();
AccessBd AccessBd = new AccessBd();
public List<Clients> FillTable()
{
try
{
//Instancia uma nova coleção de cliente
List<Clients> clientCollection = new List<Clients>();
AccessBd.ParameterCleaner();
//Coloca a consulta dentro do DataTable
DataTable dataTableCli = AccessBd.ExecuteSelect(CommandType.Text, "SELECT IDCLIENTE, DATACAD, CPF, NOME, SEXO, DDD, NUMERO,TIPO FROM V_CLIENTE");
//Percorre Cada linha do DataTable, transformando-as em um objeto Client
foreach (DataRow row in dataTableCli.Rows)
{
//Como o atributo vem do BD com o tipo Object, se faz necessário sua conversão
int idCli = Convert.ToInt32(row["IDCLIENTE"]);
string nome = Convert.ToString(row["NOME"]);
char sexo = Convert.ToChar(row["SEXO"]);
string ddd = Convert.ToString(row["DDD"]);
string numero = Convert.ToString(row["NUMERO"]);
clientCollection.Add(new Clients(idCli, nome, sexo, ddd, numero));
}
clientCollection.Sort((x, y) => x.NomeCliente.CompareTo(y.NomeCliente));
return clientCollection;
}
catch (Exception e)
{
throw new Exception("Erro ao Carregar o Banco de dados: " + e.Message);
}
}
}
You make different queries for references and or assemble a Dataset
– Leandro Angelo
I’m pretty new to object-oriented programming. Could you give me an example of how I do the first and second options?
– ArchL
https://docs.microsoft.com/pt-br/dotnet/framework/data/adonet/populating-a-dataset-from-a-dataadapter?redirectedfrom=MSDN
– Leandro Angelo