Skip to content

Instantly share code, notes, and snippets.

@marciol
Created August 11, 2012 23:24
Show Gist options
  • Save marciol/3327784 to your computer and use it in GitHub Desktop.
Save marciol/3327784 to your computer and use it in GitHub Desktop.
Genial solution to return anonymous types for a function using Dapper and lambda expressions
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Dapper;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var res = CreditCards(t =>
new {
CreditCardId = t["CreditCardID"],
CardType = t["CardType"],
CardNumber = t["CardNumber"],
ExpMonth = t["ExpMonth"],
ExpYear = t["ExpYear"]
});
Console.Write("");
}
private static IEnumerable<T> Query<T>(string queryString, object parameters, Func<IDictionary<string, object>, T> map)
{
var sqlConnection = @"Data Source=Machine\SQLEXPRESS;Initial Catalog=AdventureWorks2012;Persist Security Info=True;User ID=sa;Password=";
using (var connection = new SqlConnection(sqlConnection))
{
connection.Open();
var data = connection.Query("select * from Sales.CreditCard where CreditCardID < @Id", new { Id = 10 });
foreach(var d in data)
yield return map.Invoke(d);
}
}
private static IEnumerable<T> CreditCards<T>(Func<IDictionary<string, object>, T> map)
{
var str = "select * from Sales.CreditCard where CreditCardID < @Id";
foreach (var d in Query(str, new { Id = 10 }, map))
yield return d;
}
}
}
@kiquenet
Copy link

(string queryString, object parameters, not used ?

@kiquenet
Copy link

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<<anonymous type: object INDICE, object ID, object TV, object ID_TV, object PRIORITE, object STATUS, object LIB_STATUS, object NIVABS, object DIA, object HORA, object FicheroCarga>>'
to

'System.Collections.Generic.IEnumerable<object[]>'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment