I'm using Entity Framework 6 in C# and have implemented my own class of DatabaseLogFormatter
to be able to format what comes out of the log.
I would like to add some more detail to the log the TEntity object type that has executed the SQL (using thes procedure DbSqlQuery<TEntity> SqlQuery(string sql, params object[] parameters)
). So if I had an entity named staff
and called staff.SqlQuery
I could in the LogCommand()
pull out that it was staff
that calling SQL. I could then put a line into my log Entity "staff" executed the command...
Put up some code for what you have so far. It's not clear from the example procedure given it wasn't an extension method. On a guess if you want an extension method that runs against a DbSet<TEntity>
...
public static class DbSetExtensions
{
public static DbSqlQuery<TEntity> SqlQuery<TEntity>(this DbSet<TEntity> dbSet, string sql, params object[] parameters) where TEntity : class
{
// Do stuff with dbSet...
Logger.Instance.Write(string.Replace("Entity \"{0}\" executed the command...", typeof(TEntity).Name));
}
}
calling code would be something like:
using( var context = new myDbContext())
{
var query = context.Orders.SqlQuery(sql);
// ...
var results = query.ToList();
}
As a static method, to access a logger you'd need to resolve it as either a static class or static Singleton. Alternatively, to just extract the name of a DbSet for use in a non-static repository method or the like:
public static class DbSetExtensions
{
public static string EntityName<TEntity>(this DbSet<TEntity> dbSet) where TEntity : class
{
return typeof(TEntity).Name;
}
}
Though without code it's a bit difficult to guess at how you intended that SqlQuery method to work...