Dapper return Identity/Seed from insert

Posted: 2015-03-12 in .Net
Tags: ,

To get the identity from the insert when using dapper return the SCOPE_IDENTITY

So far has been working reasonably well.

Example below:

public class AccountingProductAccess : IAccountingProductAccess
  private readonly IDataAccess _dataAccess;

  public AccountingProductAccess(IDataAccess dataAccess)
    _dataAccess = dataAccess;

  public int CreateProductName(string name)
    const string sql = @" insert into dbo.Product (Name)
                        values (@Name);
                        SELECT CAST(SCOPE_IDENTITY() as int)";

    using (var connection = _dataAccess.GetOpenConnection())
        var id = connection.Query<int>(sql, new { Name = name }).Single();
        return id;

public class DataBaseAccess : IDataAccess
   private readonly IDatabaseSettings _databaseSettings;

   public DataBaseAccess(IDatabaseSettings databaseSettings)
     _databaseSettings = databaseSettings;

   public SqlConnection GetOpenConnection()
     var connection = new SqlConnection(_databaseSettings.ConnectionString);
     return connection;

 public class NorthwindDatabaseSettings : IDatabaseSettings
     public string ConnectionString
         get { return ConfigurationManager.ConnectionStrings["NorthwindDatabase"].ConnectionString; }

Is a simple post but I keep forgetting.


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s