Last active
March 3, 2018 18:21
-
-
Save AlbertoMonteiro/074e89ebdc7b1465d50852a012305cc1 to your computer and use it in GitHub Desktop.
IEnumerable and Entity Framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Data.SqlClient; | |
using System.Collections.Generic; | |
using System.Data.Entity; | |
using System.Linq; | |
namespace ConsoleApp2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
using (var ctx = new MeuCtx()) | |
{ | |
ctx.Database.Delete(); | |
ctx.Database.Create(); | |
ctx.Pessoas.Add(new Pessoa { Nome = "Alberto 1", Carros = new List<Carro> { new Carro { Modelo = "Gol" } } }); | |
ctx.Pessoas.Add(new Pessoa { Nome = "Alberto 2", Carros = new List<Carro> { new Carro { Modelo = "Gol" } } }); | |
ctx.Pessoas.Add(new Pessoa { Nome = "Alberto 3", Carros = new List<Carro> { new Carro { Modelo = "Gol" } } }); | |
ctx.Pessoas.Add(new Pessoa { Nome = "Alberto 4", Carros = new List<Carro> { new Carro { Modelo = "Gol" } } }); | |
ctx.Pessoas.Add(new Pessoa { Nome = "Alberto 5", Carros = new List<Carro> { new Carro { Modelo = "Gol" } } }); | |
ctx.SaveChanges(); | |
} | |
using (var ctx = new MeuCtx()) | |
{ | |
ctx.Database.Log = Console.WriteLine; | |
DoIt(ctx.Pessoas); | |
} | |
using (var ctx = new MeuCtx()) | |
{ | |
Console.WriteLine("Usando ADO.NET puro"); | |
DoIt(Pessoas(ctx.Database.Connection.ConnectionString)); | |
} | |
} | |
private static IEnumerable<Pessoa> Pessoas(string connectionString) | |
{ | |
using(var connection = new SqlConnection(connectionString)) | |
{ | |
var command = connection.CreateCommand(); | |
command.CommandText = "SELECT * FROM Pessoas"; | |
connection.Open(); | |
using (var dataReader = command.ExecuteReader()) | |
while(dataReader.Read()) | |
yield return new Pessoa { Id = dataReader.GetInt64(0), Nome = dataReader.GetString(1) }; | |
} | |
} | |
private static void DoIt(IEnumerable<Pessoa> pessoas) | |
{ | |
foreach (var pessoa in pessoas) | |
Console.WriteLine(pessoa.Nome); | |
foreach (var pessoa in pessoas) | |
Console.WriteLine(pessoa.Nome); | |
} | |
} | |
public class MeuCtx : DbContext | |
{ | |
public DbSet<Pessoa> Pessoas { get; set; } | |
public DbSet<Carro> Carros { get; set; } | |
} | |
public class Pessoa | |
{ | |
public long Id { get; set; } | |
public string Nome { get; set; } | |
public virtual ICollection<Carro> Carros { get; set; } | |
} | |
public class Carro | |
{ | |
public long Id { get; set; } | |
public string Modelo { get; set; } | |
public virtual ICollection<Pessoa> Pessoas { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment