Getting TEntity type in logging

.net c# entity-framework entity-framework-6

Question

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...

1
0
8/22/2018 5:46:25 AM

Popular Answer

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...

0
8/22/2018 5:44:41 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow