using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq.Expressions;
using iiie.Logs.DataAccess;
using iiie.Logs.DBO;
namespace iiie.WebApiUtils.BusinessManager
{
///
/// Helper for SQL Server data access
///
public abstract class SqlServerBasicManager
where TDbObject : class
where TEntities : DbContext, new()
where TThis : SqlServerBasicManager, new()
{
///
/// Return the table to be used
///
/// The database
/// The table instance
public abstract DbSet GetTable(TEntities db);
///
/// Return the database table to use
///
/// The database instance
/// The table
public static DbSet GetTableStatic(TEntities db)
{
var type = new TThis();
return type.GetTable(db);
}
///
/// Get a predicate form the given keys and values
///
/// The keys and values to select data
/// The predicate
public static Expression> GetExpression(params KeyValuePair[] keys)
{
var param = Expression.Parameter(typeof(TDbObject), "x");
Expression totalExp = null;
foreach (var pair in keys)
{
var equalExp = Expression.Equal(Expression.Property(param, pair.Key), Expression.Constant(pair.Value));
totalExp = totalExp == null ? equalExp : Expression.And(equalExp, totalExp);
}
return Expression.Lambda>(totalExp, param);
}
///
/// Execute SQL quries in try catch
///
/// The queries to be performed
/// The result or an error
public static OpResult Execute(Func, OpResult> func)
{
try
{
using (var db = new TEntities())
{
var table = GetTableStatic(db);
return func(db, table);
}
}
catch (Exception e)
{
return Logger.Error(ResultStatus.DBError, e);
}
}
}
}