Skip to content

Instantly share code, notes, and snippets.

@upnxt
Last active August 29, 2015 14:26
Show Gist options
  • Save upnxt/d29da2d572e3ca6e5568 to your computer and use it in GitHub Desktop.
Save upnxt/d29da2d572e3ca6e5568 to your computer and use it in GitHub Desktop.
public class AnimalService : IAnimalService
{
private readonly IDatabase _database;
public AnimalService(IDatabase database)
{
_database = database;
}
public IEnumerable<Animal> GetAllAnimals()
{
return _database.Query(new GetAllAnimals());
}
public IEnumerable<Animal> GetAnimalsByCommonName(CommonName commonName)
{
return _database.Query(new GetAnimalsByCommonName(commonName));
}
public void Save(Animal animal)
{
_database.Execute(new SaveAnimal(animal));
}
}
public class GetAllAnimals : IQuery<IList<Animal>>
{
public IList<Animal> Execute(ISession session)
{
return session.Query<Animal>("SELECT * FROM Animals").ToList();
}
}
public interface ICommand
{
void Execute(ISession session);
}
public interface IDapperContext : IDisposable
{
IDbConnection Connection { get; }
T Transaction<T>(Func<IDbTransaction, T> query);
IDbTransaction BeginTransaction();
void Commit();
void Rollback();
}
public interface IQuery<out T>
{
T Execute(ISession session);
}
public class SaveAnimal : ICommand
{
private readonly Animal _animal;
public SaveAnimal(Animal animal)
{
_animal = animal;
}
public void Execute(ISession session)
{
if (_animal.Id > 0)
{
session.Execute("UPDATE Animals SET Name = @Name, CommonName = @CommonName WHERE Id = @Id", new { _animal.Id, _animal.Name, _animal.CommonName });
return;
}
session.Execute("INSERT INTO Animals (Name, CommonName) VALUES (@Name, @CommonName)", new { _animal.Name, _animal.CommonName });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment