CodeSnips

Wednesday, February 12, 2014

LINQPad4 Command Line And Dapper Via Nuget Just For Fun

LINQPad4 recently added a command line runner "lprun.exe" which provides some very useful and fun things to do with LINQPAD scripts (or even code fragments).  I'll finish this post with an example, but first I was surprised to realize that you can, via the F4 command, reference Nuget packages in a linqpad script. For additional fun I thought I'd add references to Dapper and DapperExtensions, a nice "micro" ORM and helper extension methods that lets you do all sorts of useful things with databases.

Let's get started:

1. In LINQPad, hit F4 to bring up the references dialog and choose "Add Nuget..." under the "Additional References" tab.
2. Search (and add) "Dapper", then "DapperExtensions".
3. Under the "Additional Namespace Imports" tab, add "Dapper" and "DapperExtensions".









 You are now ready to do some Dapper things in LINQPad4. The logical question might be "why?" as we are able to do SQL linq stuff in LINQPad4 right out of the box. But, there are some useful things you can do in Dapper and there's no reason you can't mix the two things together. Plus, this is for play as much as for anything else. Let's have some fun.

This script gives a small example of how to obtain the connection string and do a little Dapper.  Note, it's interesting that you can do pretty much anything, such as DDL (commented out line), with Dapper - as opposed to linq for SQL. This simply creates some output.

// Dapper stuff
// import Dapper;
// import DapperExtensions;

var conn = new SqlConnection(Connection.ConnectionString);
var results = conn.Query("SELECT * FROM ROLES").ToList();

foreach (IDictionary r in results) {
    Console.WriteLine("\"{0}\",\"{1}\",{2}",
                      r["Rolename"],r["ApplicationName"],r["COUNT"]);
}

//conn.Execute("ALTER TABLE ROLES ADD COUNT DECIMAL (19,6)");

Now, you are able to run this script, using the new lprun.exe utility provided with LINQPad4, at the command line.











I'd recommend checking out the various options, especially the format options, available with this tool. For those who'd like to combine powershell scripting along with some database work, this could be a powerful, and yes, fun, way to do things.

Have fun!