Getting TEntity type in logging

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

Question

Using C# and Entity Framework 6, I've created my own class ofDatabaseLogFormatter to have the ability to format the log's output.

I want to add extra information to the SQL execution log for the TEntity object type using this technique.DbSqlQuery<TEntity> SqlQuery(string sql, params object[] parameters) Therefore, suppose I had a thing calledstaff then calledstaff.SqlQuery I may in theLogCommand() remove that which it wasstaff calling SQL, etc. Then I could add a line to my log.Entity "staff" executed the command...

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

Popular Answer

Add some code to what you've got so far. Given that it wasn't an extension method, the sample technique doesn't make it apparent. If you want a guess-based extension technique that tests against aDbSet<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 may look like this:

using( var context = new myDbContext())
{
   var query = context.Orders.SqlQuery(sql);
   // ...
   var results = query.ToList();
}

To access a logger as a static method, you would need to resolve it as a static class or static Singleton. As an alternative, you may just extract a DbSet's name for usage in a method for a non-static repository or anything similar:

public static class DbSetExtensions
{
   public static string EntityName<TEntity>(this DbSet<TEntity> dbSet) where TEntity : class
   {
      return typeof(TEntity).Name;
   }
}

Although it's a little challenging to determine how you wanted that SqlQuery function to operate without any code...

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