Skip to content

Instantly share code, notes, and snippets.

@AlbertoMonteiro
Last active December 11, 2017 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlbertoMonteiro/8606a91a5504ea9c21dbd950b8740385 to your computer and use it in GitHub Desktop.
Save AlbertoMonteiro/8606a91a5504ea9c21dbd950b8740385 to your computer and use it in GitHub Desktop.
EF com IEnumerable gerando Multiple Enumeration
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