Skip to content

Instantly share code, notes, and snippets.

@JulianRooze
Created November 20, 2012 16:01
Show Gist options
  • Save JulianRooze/4118813 to your computer and use it in GitHub Desktop.
Save JulianRooze/4118813 to your computer and use it in GitHub Desktop.
Dapper includes
public IList<Stock> ListStock(int? productID, int? orgID, StockLabel? label, ProductConditionTypes? condition, IList<string> includes)
{
var builder = new SqlBuilder();
var template = builder.AddTemplate(@"
select /**select**/ from Stock s
/**join**/
/**where**/");
if (productID.HasValue)
{
builder.Where("s.ProductID = @productID", new { productID });
}
if (orgID.HasValue)
{
builder.Where("s.OrganizationUnitID = @orgID", new { orgID });
}
if (label.HasValue)
{
builder.Where("s.StockLabelID = @labelID", new { labelID = (int)label });
}
if (condition.HasValue)
{
builder.Where("s.ProductConditionID = @conditionID", new { conditionID = (int)condition });
}
builder.Where("s.QuantityOnHand > 0");
builder.Select("s.*");
bool includeProduct = false, includeOrg = false;
if (includes != null && includes.Contains("Product"))
{
builder.Join("Products p on s.ProductID = p.ID");
builder.Select("p.*");
includeProduct = true;
}
if (includes != null && includes.Contains("OrganizationUnit"))
{
builder.Join("OrganizationUnits o on s.OrganizationUnitID = o.ID");
builder.Select("o.*");
includeOrg = true;
}
using (var conn = _dapper.OpenConnection())
{
if (!includeOrg && !includeProduct)
{
var results = conn.Query<Stock>(template.RawSql, template.Parameters);
return results as List<Stock>;
}
else
{
IEnumerable<Stock> results = null;
if (includeProduct && !includeOrg)
{
results = conn.Query<Stock, Product, Stock>(template.RawSql,
(s, p) =>
{
s.Product = p;
return s;
},
template.Parameters);
}
else if (!includeProduct && includeOrg)
{
results = conn.Query<Stock, OrganizationUnit, Stock>(template.RawSql,
(s, o) =>
{
s.OrganizationUnit = o;
return s;
},
template.Parameters);
}
else if (includeOrg && includeProduct)
{
results = conn.Query<Stock, Product, OrganizationUnit, Stock>(template.RawSql,
(s, p, o) =>
{
s.Product = p;
s.OrganizationUnit = o;
return s;
},
template.Parameters);
}
return results as List<Stock>;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment