Ado.Net and Entity in the same project

0

I took a test to do and it is mandatory to use Ado.Net, but it would be a differential use of Entity. I'm kind of confused about that. Ado.Net and Entity give dancing?

    
asked by anonymous 06.12.2017 / 18:51

1 answer

1

If the question is whether the two work together, yes the two can work together

See the example I mounted

class Program
{
    static void Main(string[] args)
    {
        InserirDados();
        UsandoAdo();
        UsandoEF();
    }

    static void InserirDados()
    {
        using (EFContext ef = new EFContext())
        {
            if (!ef.Pessoas.Any())
            {
                for (int i = 0; i < 10; i++)
                {
                    ef.Pessoas.Add(new Pessoa() { Nome = $"Nome {i}" });
                }

                ef.SaveChanges();
            }
        }
    }

    static void UsandoAdo()
    {
        using (SqlConnection ado = new SqlConnection(ConfigurationManager.ConnectionStrings["EFContext"].ToString()))
        {
            string select = "select * from pessoas";
            SqlCommand command = new SqlCommand(select, ado);
            ado.Open();
            var dr = command.ExecuteReader();
            while(dr.Read())
            {
                Console.WriteLine($"Usando ADO {dr["Nome"]}");
            }
        }
    }

    static void UsandoEF()
    {
        using (EFContext ef = new EFContext())
        {
            foreach(var pessoa in ef.Pessoas.ToList())
            {
                Console.WriteLine($"Usando EF {pessoa.Nome}");
            }
        }
    }
}

public class EFContext : DbContext
{
    public DbSet<Pessoa> Pessoas { get; set; }
}

public class Pessoa
{
    [Key]
    public int Id { get; set; }

    public string Nome { get; set; }
}

I added the sample source code to my github

    
06.12.2017 / 19:07