Is it possible to use anonymous types with Dapper?
I can see how you can use dynamic i.e.
connection.Query<dynamic>(blah, blah, blah)
is it then possible to do a
.Select(p=> new { A, B ,C })
or some variation of that afterwards?
Edit
I thought I'd show you how I am using Dapper at the moment. I tend to cache (using an InMemoryCache) data so I just do one big query at the beginning (which is super quick using Dapper) then I use Linq to sort it all out in my Repository.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Linq;
using Dapper;
namespace SomeNamespace.Data
{
public class DapperDataContext : IDisposable
{
private readonly string _connectionString;
private readonly DbProviderFactory _provider;
private readonly string _providerName;
public DapperDataContext()
{
const string connectionStringName = " DataContextConnectionString";
_connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
_providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName;
_provider = DbProviderFactories.GetFactory(_providerName);
}
public IEnumerable<MyDataView> MyData1 { get; private set; }
public IEnumerable<MyDataView> MyData2 { get; private set; }
protected string SqlSelectMyTable1Query
{
get
{
return @"SELECT Id, A, B, C from table1Name";
}
}
protected string SqlSelectMyTable2Query
{
get
{
return @"SELECT Id, A, B, C from table2Name";
}
}
public void Dispose()
{
}
public void Refresh()
{
using (var connection = _provider.CreateConnection())
{
// blow up if null
connection.ConnectionString = _connectionString;
connection.Open();
var sql = String.Join(" ",
new[]
{
SqlSelectMyTable1Query,
SqlSelectMyTable2Query
});
using (var multi = connection.QueryMultiple(sql))
{
MyData1 = multi.Read<MyDataView>().ToList();
MyData2 = multi.Read<MyDataView>().ToList();
}
}
}
public class MyDataView
{
public long Id { get; set; }
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
}
}
The InMemoryCache looks like this
namespace Libs.Web
{
public class InMemoryCache : ICacheService
{
#region ICacheService Members
public T Get<T>(string cacheId, Func<T> getItemCallback) where T : class
{
var item = HttpRuntime.Cache.Get(cacheId) as T;
if (item == null)
{
item = getItemCallback();
HttpContext.Current.Cache.Insert(cacheId, item);
}
return item;
}
public void Clear(string cacheId)
{
HttpContext.Current.Cache.Remove(cacheId);
}
#endregion
}
public interface ICacheService
{
T Get<T>(string cacheId, Func<T> getItemCallback) where T : class;
void Clear(string cacheId);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…