I'm just beginning my first MVC project using Dapper (and Dapper.Contrib) instead of EF. I'm trying to make sure I'm using the proper syntax when using it. Searching the web, I can see that as Dapper has evolved, so has some of its requirements and syntax. Is there an up to date document that shows best practices for using Dapper in 2016?
Specifically, my questions are:
Do I need to open and close the connection? It looks like Dapper used to require it but may not any longer.
Using Dapper.Contrib, do I need to encapsulate my code in a 'using' call or will Dapper take care of disposing itself automatically now?
Which way is recommended?
private string dbconn = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
public Company Add(Company company)
{
using (SqlConnection cn = new SqlConnection(dbconn))
{
cn.Open();
var id = cn.Insert(company);
cn.Close();
company.id = Convert.ToInt16(id);
}
return company;
}
OR
private IDbConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
public Company Add(Company company)
{
var id = cn.Insert(company);
company.id = Convert.ToInt16(id);
return company;
}