Dapper和匿名类型
Dapper和匿名类型
是否可以在Dapper中使用匿名类型?
我知道可以使用dynamic,例如:
connection.Query
然后是否可以使用以下方式之一:
.Select(p => new { A, B, C })
或一些变体?
编辑
我想展示一下我目前如何使用Dapper。我倾向于使用一个InMemoryCache来缓存数据,所以我只需要在开始时进行一次大型查询(使用Dapper非常快),然后我使用Linq在我的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 IEnumerableMyData1 { get; private set; } public IEnumerable 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()) { // 如果为null则抛出异常 connection.ConnectionString = _connectionString; connection.Open(); var sql = String.Join(" ", new[] { SqlSelectMyTable1Query, SqlSelectMyTable2Query }); using (var multi = connection.QueryMultiple(sql)) { MyData1 = multi.Read ().ToList(); MyData2 = multi.Read ().ToList(); } } } public class MyDataView { public long Id { get; set; } public string A { get; set; } public string B { get; set; } public string C { get; set; } } } }
InMemoryCache看起来像这样
namespace Libs.Web { public class InMemoryCache : ICacheService { #region ICacheService Members public T Get(string cacheId, Func 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 (string cacheId, Func getItemCallback) where T : class; void Clear(string cacheId); } }