Quick Dapper Repo.


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.

We will create an author model named Author.cs and I typically put these into a folder at /Models:
public class Author
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

We will create the interface named IAuthorRepository.cs and I typically put these into a folder named /Interfaces:
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);
}

We will create the repository named AuthorRepositoryc.cs and I typically put these into a folder named /Repositories:
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();
}
}

rickthehat

Travel, Food, Vikings, Travel, Vood, Vikings, Travel, Food, Vikings, Travel, Food, Vikings & Einstok Beer from Iceland

Leave a Comment