Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper and anonymous Types

Tags:

c#

orm

dapper

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); } } 
like image 726
Peter Avatar asked May 27 '11 02:05

Peter


People also ask

What are anonymous data types?

Anonymous types are class types that derive directly from object , and that cannot be cast to any type except object . The compiler provides a name for each anonymous type, although your application cannot access it.

What are difference between anonymous and dynamic types?

Anonymous type is a class type that contain one or more read only properties whereas dynamic can be any type it may be any type integer, string, object or class. Anonymous types are assigned types by the compiler. Anonymous type is directly derived from System.

What is anonymous in C#?

In C#, an anonymous type is a type (class) without any name that can contain public read-only properties only. It cannot contain other members, such as fields, methods, events, etc. You create an anonymous type using the new operator with an object initializer syntax.

What is the difference between an anonymous type and a regular data type C#?

What is Anonymous Types in C#? Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.


1 Answers

Is it possible to use anonymous types with Dapper?

Sure see the non-generic Query override, it return a dynamic IDictionary<string, object> this object is an expando that can either be cast or accessed with dot notation.

Eg:

var v = connection.Query("select 1 as a, 2 as b").First();  Console.Write("{0} {1}",v.a, v.b) // prints: 1 2 

is it then possible to do a .Select

Sure, you get an IEnumerable<dynamic> ... you can run anything you want on that.

like image 78
Sam Saffron Avatar answered Oct 10 '22 23:10

Sam Saffron