I love to use the Dapper ORM from the folks at StackOverflow and it's nice to have quick reference that I can fall back on with a quick example that shows how to create a model, interface and repository.
I'm sure this example is out there somewhere in the interewebs but I can never seem to find it when I need it so if you know where this code came from please LMK so I can give proper attribution.
public class Author
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public interface IAuthorRepository
{
Author Find(int id);
List<Author> GetAll();
Author Add(Author author);
Author Update(Author author);
void Remove(int id);
void Save(Author author);
}
public class AuthorRepository : IAuthorRepository
{
private readonly IDbConnection _db =
new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
public Author Find(int id) {
return _db.Query<Author>("SELECT * FROM Authors WHERE Id = @Id", new { id }).SingleOrDefault();
}
public List<Author> GetAll() {
return _db.Query<Author>("SELECT * FROM Authors").ToList();
}
public Author Add(Author author) {
author.FirstName = author.FirstName.Trim();
author.LastName = author.LastName.Trim();
const string sql = "INSERT INTO Authors (FirstName, LastName) VALUES (@FirstName, @LastName); " +
"SELECT CAST(SCOPE_IDENTITY() AS int)";
var id = _db.Query<int>(sql, author).Single();
author.Id = id;
return author;
}
public Author Update(Author author) {
author.FirstName = author.FirstName.Trim();
author.LastName = author.LastName.Trim();
const string sql = "UPDATE Authors " +
"SET FirstName = @FirstName, " +
"LastName = @LastName " +
"WHERE Id = @Id";
_db.Execute(sql, author);
return author;
}
public void Remove(int id) {
var sql = ("DELETE FROM Authors Where Id = " + id + "");
_db.Execute(sql);
}
public void Save(Author employee) {
throw new NotImplementedException();
}
}