Skip to content

Can I use this with Dapper?

Grauenwolf edited this page Apr 16, 2016 · 6 revisions

Can I use this with Dapper?

If you are currently using Dapper or another connection-oriented ORM, you can mix Dapper and Chain operations together. Here is a quick example:

using (var connection = new SqlConnection(s_ConnectionString))
{
    var originalDog = new Dog() { Age = 2, Name = "Fido", Weight = 2.5f };

    //Let try inserting a record
    //const string insertSql = "INSERT INTO Dog (Age, Name, Weight) OUTPUT Inserted.Id VALUES (@Age, @Name, @Weight);";
    //var key = connection.ExecuteScalar<Guid>(insertSql, originalDog);
    var key = connection.AsDataSource().Insert("Dog", originalDog).ToGuid().Execute();
            
    //const string selectSql = "SELECT Age, Name, Weight FROM Dog WHERE Id = @Id;";
    //var fetchedDog = connection.Query<Dog>(selectSql, new { Id = key }).Single();
    var fetchedDog = connection.AsDataSource().GetByKey("Dog", key).ToObject<Dog>().Execute();
}

This connection.AsDataSource() extension method wraps the open connection with a DataSource, which in turn exposes all of the Chain functionality. Using this, you can selectively replace repetitive calls such as insert/update while continuing to use Dapper for more complex operations.

You can also use transaction.AsDataSource(), which essentially works the same way.

Can I use this with Entity Framework?

Technically yes, but it’s a bit harder that we'd like. Assuming that you have a database context, you can write:

((SqlConnection)context.Database.Connection).ToDataSource()

This assumes that your EF DBContext is currently attached to a SQL Server database. If you are attached to SQLite or another provider at the moment, the cast will fail. But rest assured that we are looking at better ways to handle this.

Clone this wiki locally