Skip to content

Instantly share code, notes, and snippets.

@dcomartin

dcomartin/Repository.cs Secret

Created Feb 10, 2021
Embed
What would you like to do?
public class ShoppingCartRepository
{
private readonly IDbConnection _connection;
public ShoppingCartRepository(IDbConnection connection)
{
_connection = connection;
}
public async Task<ShoppingCartEventDomain> GetShoppingCart(Guid shoppingCartId)
{
var shoppingCart = await _connection.QueryFirstAsync<ShoppingCart>("SELECT CustomerId FROM ShoppingCarts WHERE ShoppingCartId=@ShopingCartId",
new {ShoppingCartId = shoppingCartId});
var items = await _connection.QueryAsync<ShoppingCartItem>("SELECT ProductId, Quantity FROM ShoppingCartItems WHERE ShoppingCartId=@ShopingCartId",
new {ShoppingCartId = shoppingCartId});
shoppingCart.Items = items.ToList();
return new ShoppingCartEventDomain(shoppingCart);
}
public async Task Save(ShoppingCartEventDomain shoppingCart)
{
var trx = _connection.BeginTransaction();
var evnts = shoppingCart.GetEvents();
foreach (var evnt in evnts)
{
if (evnt is ItemAdded itemAdded)
{
await ItemAdded(itemAdded, trx);
}
else if (evnt is QuantityIncremented quantityIncremented)
{
await QuantityIncremented(quantityIncremented, trx);
}
else if (evnt is ItemRemoved itemRemoved)
{
await ItemRemoved(itemRemoved, trx);
}
}
trx.Commit();
}
private async Task ItemAdded(ItemAdded evnt, IDbTransaction trx)
{
await _connection.ExecuteAsync("INSERT INTO ShoppingCartItems (ShoppingCartId, ProductId, Quantity, Price) VALUES (@ShoppingCartId, @ProductId, @Quantity, @Price)",
new
{
ShoppingCartId = evnt.ShoppingCartId,
ProductID = evnt.ProductId,
Quantity = evnt.Quantity,
Price = evnt.Price
}, trx);
}
private async Task QuantityIncremented(QuantityIncremented evnt, IDbTransaction trx)
{
await _connection.ExecuteAsync("UPDATE ShoppingCartItems SET Quantity=Quantity+@Quantity WHERE ShoppingCartId=@ShoppingCartId AND ProductID=@ProductId",
new
{
ShoppingCartId = evnt.ShoppingCartId,
ProductID = evnt.ProductId,
Quantity = evnt.Quantity,
}, trx);
}
private async Task ItemRemoved(ItemRemoved evnt, IDbTransaction trx)
{
await _connection.ExecuteAsync("DELETE FROM ShoppingCartItems WHERE ShoppingCartId=@ShoppingCartId AND ProductId=@ProductId",
new
{
ShoppingCartId = evnt.ShoppingCartId,
ProductID = evnt.ProductId
}, trx);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment