Ado.Net and Entity in the same project

Asked

Viewed 134 times

0

I took a test to do and it is mandatory to use Ado.Net, but it would be a differential the use of Entity. I’m a little confused about this. Ado.Net and Entity gives ball?

  • What do you mean, dance? Talk about wearing both in the same project?

  • 1

    I believe you are asking if the two work together and it is correct to do so, yes you can use, just dosar and know how to do but, it works smoothly, including many utlizar Entity and Dapper in the same application.

  • It’s a dance, man. But I don’t know.. I prefer to be with only one, there are people who use Dapper and EF as @Virgilionovic commented, I am particularly more adept at Dapper, when the thing gets complex in EF and you need to do maintenance in some query via Linq I prefer to tinker with SQL rather than head-banging with Line and syntax when you have huge relationships

1 answer

1


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

Look at the example I put together

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 example source code to my github

Browser other questions tagged

You are not signed in. Login or sign up in order to post.