In an article about implementing a repository with Dapper (Using Dapper.NET ORM...), there is the following code:
public class UserRepository : IUserRepository
{
private IDbConnection _db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
public List<User> GetAll()
{
return this._db.Query<User>("SELECT * FROM Users").ToList();
}
public User Find(int id)
{
return this._db.Query<User>("SELECT * FROM Users WHERE UserID = @UserID", new { id }).SingleOrDefault();
}
public User Add(User user)
{
var sqlQuery = "INSERT INTO Users (FirstName, LastName, Email) VALUES(@FirstName, @LastName, @Email); " + "SELECT CAST(SCOPE_IDENTITY() as int)";
var userId = this._db.Query<int>(sqlQuery, user).Single();
user.UserID = userId;
return user;
}
}
Regarding the private IDbConnection, why is this never opened or closed in the individual methods? I've seen this elsewhere as well. Is there some sugar around this pattern? My instinct is to wrap each return in a using followed by an _db.Open(); like below, but, again, I've seen this not being done in several other references on the web.
public List<User> GetAll()
{
using (_db) //or (IDbConnection _db = new SqlConnection(myConnectionString))
{
_db.Open();
return this._db.Query<User>("SELECT * FROM Users").ToList();
}
}
Open
if needed, but I agree that it would be better to create a new connection in ausing
each time. – juharr Mar 7 '16 at 18:36AsList()
rather thanToList()
, you'll avoid a list allocation – Marc Gravell♦ Mar 7 '16 at 20:43