Skip to content

Instantly share code, notes, and snippets.

@AlbertoMonteiro
Created October 31, 2017 20:34
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/1f5fef60eb1e520b3d15d2903dc0f3e6 to your computer and use it in GitHub Desktop.
Save AlbertoMonteiro/1f5fef60eb1e520b3d15d2903dc0f3e6 to your computer and use it in GitHub Desktop.
Complex model resolution with raw query using Entity Framework and Slapper.AutoMapper
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Dynamic;
using System.Linq;
namespace EfSqlQueryTree
{
class Program
{
static void Main(string[] args)
{
var efContext = new MeuContexto();
efContext.Database.CreateIfNotExists();
AdicionarUmaPessoa(efContext);
var pessoasDynamic = efContext.Database.SuperSqlQuery(@"SELECT
[p].[Id] AS [Id],
[p].[Nome] AS [Nome],
[c].[Id] AS [Carros_Id],
[c].[Modelo] AS [Carros_Modelo],
[c].[Marca] AS [Carros_Marca]
FROM [dbo].[Pessoas] AS [p]
LEFT JOIN [dbo].[Carroes] AS [c] ON [p].[Id] = [c].[Pessoa_Id]").ToList();
var pessoas = Slapper.AutoMapper.MapDynamic<PessoaVm>(pessoasDynamic);
foreach (var pessoa in pessoas)
{
Console.WriteLine(pessoa.Id);
Console.WriteLine(pessoa.Nome);
foreach (var pessoaCarro in pessoa.Carros)
{
Console.WriteLine(pessoaCarro.Marca);
Console.WriteLine(pessoaCarro.Modelo);
}
Console.WriteLine("#### --------------------------- ####");
}
}
private static void AdicionarUmaPessoa(MeuContexto efContext)
{
if (!efContext.Pessoas.Any())
{
efContext.Pessoas.Add(new Pessoa()
{
Nome = "Alberto Monteiro",
Carros = new List<Carro>
{
new Carro {Marca = "BMW", Modelo = "320i"}
}
});
efContext.SaveChanges();
}
}
}
class MeuContexto : 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 ICollection<Carro> Carros { get; set; }
}
public class Carro
{
public long Id { get; set; }
public string Modelo { get; set; }
public string Marca { get; set; }
}
public class PessoaVm
{
public long Id { get; set; }
public string Nome { get; set; }
public ICollection<CarroVm> Carros { get; set; }
}
public class CarroVm
{
public long Id { get; set; }
public string Modelo { get; set; }
public string Marca { get; set; }
}
public static class DatabaseExtensions
{
public static IEnumerable<dynamic> SuperSqlQuery(this Database db, string query)
{
var dbCommand = db.Connection.CreateCommand();
dbCommand.CommandText = query;
dbCommand.Connection.Open();
using (var dbDataReader = dbCommand.ExecuteReader())
while (dbDataReader.Read())
{
var obj = new ExpandoObject() as IDictionary<string, object>;
for (var i = 0; i < dbDataReader.FieldCount; i++)
obj.Add(dbDataReader.GetName(i), dbDataReader.GetValue(i));
yield return obj;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment