Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created February 24, 2021 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcomartin/b3729857e17b858e30a4c69996e392dd to your computer and use it in GitHub Desktop.
Save dcomartin/b3729857e17b858e30a4c69996e392dd to your computer and use it in GitHub Desktop.
public class ProjectionBuilder
{
private readonly ProductDbContext _dbContext;
public ProjectionBuilder(ProductDbContext dbContext)
{
_dbContext = dbContext;
}
public void ReceiveEvent(IEvent evnt)
{
switch (evnt)
{
case ProductShipped shipProduct:
Apply(shipProduct);
break;
case ProductReceived receiveProduct:
Apply(receiveProduct);
break;
}
}
public Product GetProduct(string sku)
{
var product = _dbContext.Products.SingleOrDefault(x => x.Sku == sku);
if (product == null)
{
product = new Product
{
Sku = sku
};
_dbContext.Products.Add(product);
}
return product;
}
private void Apply(ProductShipped shipProduct)
{
var product = GetProduct(shipProduct.Sku);
product.Shipped += shipProduct.Quantity;
_dbContext.SaveChanges();
}
private void Apply(ProductReceived productReceived)
{
var state = GetProduct(productReceived.Sku);
state.Received += productReceived.Quantity;
_dbContext.SaveChanges();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment