This works nicely for quick reads. Requires no mappings or any of that junk. Just a DataReader shaped to a type.
Edit: Because this is my first day to ever work with EF, my first attempt at this was more complicated (you can see this evolution at the gist). After removing my useless code, you can see it’s just Entity Framework. Sadly I can’t take any credit. Still – this IS cool. Fast, super easy, typed queries with only framework dependencies. I was surprised to see it supported the mapping-less projections. Perfect for all of those fancy persistent view model scenarios all the cool CQRS kids are doing.
using System; using System.Collections.Generic; using System.Data.Entity; public static class Effin { public static IEnumerable<T> Query<T> (this string connectionStringName, string sql, params object[] parameters) { return new DbContext(connectionStringName) .Database.SqlQuery<T>(sql, parameters); } } public class Example { public void UsingEffin() { IEnumerable<Name> names = "data".Query<Name>("select FirstName from Person"); foreach (var name in names) { Console.WriteLine(name.FirstName); } } public class Name { public string FirstName { get; set; } } }
Pingback: Dew Drop – March 5, 2011 | Alvin Ashcraft's Morning Dew