Simple reads with Entity Framework

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; }
    }
}
About these ads
This entry was posted in Tools. Bookmark the permalink.

2 Responses to Simple reads with Entity Framework

  1. Pingback: Dew Drop – March 5, 2011 | Alvin Ashcraft's Morning Dew

  2. Pingback: Interesting .NET Links - March 6 , 2011 | TechBlog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s