Last active
December 11, 2017 14:32
-
-
Save AlbertoMonteiro/8606a91a5504ea9c21dbd950b8740385 to your computer and use it in GitHub Desktop.
EF com IEnumerable gerando Multiple Enumeration
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.Collections.Generic; | |
using System.Data; | |
using System.Data.Entity; | |
using System.Data.SqlClient; | |
using System.Linq; | |
namespace ConsoleApp5 | |
{ | |
class Program | |
{ | |
private static SuperCtx _superCtx; | |
static void Main(string[] args) | |
{ | |
Console.ForegroundColor = ConsoleColor.White; | |
using (var ctx = new SuperCtx()) | |
{ | |
if (!ctx.Database.Exists()) | |
{ | |
ctx.Database.CreateIfNotExists(); | |
ctx.Pessoas.Add(new Pessoa() { Nome = "Alberto" }); | |
ctx.SaveChanges(); | |
Console.WriteLine("Criado DB"); | |
} | |
} | |
var pessoas = ObterPessoas(); | |
Console.WriteLine("# Primeira vez"); | |
foreach (var pessoa in pessoas) | |
Console.WriteLine(pessoa.Nome); | |
InserirNovaPessoaViaSqlCommand(); | |
Console.WriteLine("# Segunda vez"); | |
foreach (var pessoa in pessoas) | |
Console.WriteLine(pessoa.Nome); | |
} | |
private static void InserirNovaPessoaViaSqlCommand() | |
{ | |
using (var outrarConexao = new SqlConnection(_superCtx.Database.Connection.ConnectionString)) | |
{ | |
outrarConexao.Open(); | |
using (var cmd = new SqlCommand("INSERT INTO Pessoas (Nome) VALUES ('Fulano')", outrarConexao)) | |
cmd.ExecuteNonQuery(); | |
} | |
} | |
private static IEnumerable<Pessoa> ObterPessoas() | |
{ | |
_superCtx = new SuperCtx(); | |
return _superCtx.Pessoas; | |
} | |
} | |
public class SuperCtx : DbContext | |
{ | |
public DbSet<Pessoa> Pessoas { get; set; } | |
} | |
public class Pessoa | |
{ | |
public long Id { get; set; } | |
public string Nome { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment