Access SQL queries Generated By Entity Framework Core 3

Create a class EntityFrameworkSqlLogger.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.Extensions.Logging;

namespace MyApp.Logging
{
    /// <summary>
    /// ILogger implementation
    /// </summary>
    public class EntityFrameworkSqlLogger : ILogger
    {
        #region Fields
        Action<EntityFrameworkSqlLogMessage> _logMessage;
        #endregion

        #region Constructor
        public EntityFrameworkSqlLogger(Action<EntityFrameworkSqlLogMessage> logMessage)
        {
            _logMessage = logMessage;
        }
        #endregion

        #region Implementation
        public IDisposable BeginScope<TState>(TState state)
        {
            return default;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (eventId.Id != 20101)
            {
                //Filter messages that aren't relevant.
                //There may be other types of messages that are relevant for other database platforms...

                return;
            }

            if (state is IReadOnlyList<KeyValuePair<string, object>> keyValuePairList)
            {
                var entityFrameworkSqlLogMessage = new EntityFrameworkSqlLogMessage
                (
                    eventId,
                    (string)keyValuePairList.FirstOrDefault(k => k.Key == "commandText").Value,
                    (string)keyValuePairList.FirstOrDefault(k => k.Key == "parameters").Value,
                    (CommandType)keyValuePairList.FirstOrDefault(k => k.Key == "commandType").Value,
                    (int)keyValuePairList.FirstOrDefault(k => k.Key == "commandTimeout").Value,
                    (string)keyValuePairList.FirstOrDefault(k => k.Key == "elapsed").Value
                );

                _logMessage(entityFrameworkSqlLogMessage);
            }
        }
        #endregion
    }
    
    /// <summary>
    /// Data model
    /// </summary>
    public class EntityFrameworkSqlLogMessage
    {
        public EntityFrameworkSqlLogMessage(
            EventId eventId,
            string commandText,
            string parameters,
            CommandType commandType,
            int commandTimeout,
            string elapsed
        )
        {
            EventId = eventId;
            CommandText = commandText;
            Parameters = parameters;
            CommandType = commandType;
            Elapsed = elapsed;
            CommandTimeout = commandTimeout;
        }

        public string Elapsed { get; }
        public int CommandTimeout { get; }
        public EventId EventId { get; }
        public string CommandText { get; }
        public string Parameters { get; }
        public CommandType CommandType { get; }
    }
    
    /// <summary>
    /// ILogger provider
    /// </summary>
    public class SingletonLoggerProvider : ILoggerProvider
    {
        #region Fields
        ILogger _logger;
        #endregion

        #region Constructor
        public SingletonLoggerProvider(ILogger logger)
        {
            _logger = logger;
        }
        #endregion

        #region Implementation
        public ILogger CreateLogger(string categoryName)
        {
            return _logger;
        }

        public void Dispose()
        {
        }
        #endregion
    }
}

Add Logger to DbContext OnConfiguring Met

public class CartServiceDbContext : DbContext
{
...

  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  {
      var entityFrameworkSqlLogger = new EntityFrameworkSqlLogger((m) =>
      {
          System.Console.WriteLine($"SQL Query:\r\n{m.CommandText}\r\nElapsed:{m.Elapsed} millisecods\r\n\r\n");
      });

      var myLoggerFactory = LoggerFactory.Create(builder =>
      {
          builder
              .AddFilter((category, level) =>
                  category == DbLoggerCategory.Database.Command.Name
                  && level == LogLevel.Information);
      });

      myLoggerFactory.AddProvider(new SingletonLoggerProvider(entityFrameworkSqlLogger));
      optionsBuilder.UseLoggerFactory(myLoggerFactory);
      DbConnectorUtils.ConfigureOptionsBuilder(optionsBuilder);
  }

...
}

References

Search for a table in all databases in a SQL Server instance

declare @sql nvarchar(max);

select @sql = 
    (select ' UNION ALL
        SELECT ' +  + quotename(name,'''') + ' as database_name,
               s.name COLLATE DATABASE_DEFAULT
                    AS schema_name,
               t.name COLLATE DATABASE_DEFAULT as table_name 
               FROM '+ quotename(name) + '.sys.tables t
               JOIN '+ quotename(name) + '.sys.schemas s
                    on s.schema_id = t.schema_id
            WHERE t.name =''table_name'''

    from sys.databases 
    where state=0
    order by [name] for xml path(''), type).value('.', 'nvarchar(max)');

set @sql = stuff(@sql, 1, 12, '') + ' order by database_name, 
                                               schema_name,
                                               table_name';

execute (@sql);

Find and Kill SQL Server orphaned transactions


select * from sys.sysprocesses where status = 'SLEEPING' and open_tran > 0


-------
declare @sp int
select @sp = spid from sys.sysprocesses where status = 'SLEEPING' and open_tran > 0


if @sp is not null
begin
    declare @tempString nvarchar (255)
    set @tempString = 'kill ' + cast (@sp as varchar (5))
    exec sp_executesql @tempString
end

Search and rename Foreign Key Name

List foreign keys:

select schema_name(fk_tab.schema_id) + '.' + fk_tab.name as foreign_table, '>-' as rel, schema_name(pk_tab.schema_id) + '.' + pk_tab.name as primary_table, substring(column_names, 1, len(column_names)-1) as [fk_columns], fk.name as fk_constraint_name from sys.foreign_keys fk inner join sys.tables fk_tab on fk_tab.object_id = fk.parent_object_id inner join sys.tables pk_tab on pk_tab.object_id = fk.referenced_object_id cross apply (select col.[name] + ', ' from sys.foreign_key_columns fk_c inner join sys.columns col on fk_c.parent_object_id = col.object_id and fk_c.parent_column_id = col.column_id where fk_c.parent_object_id = fk_tab.object_id and fk_c.constraint_object_id = fk.object_id order by col.column_id for xml path ('') ) D (column_names) order by schema_name(fk_tab.schema_id) + '.' + fk_tab.name, schema_name(pk_tab.schema_id) + '.' + pk_tab.name

Search Primary keys:

SELECT KU.table_name as TABLENAME, column_name as PRIMARYKEYCOLUMN, KU.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND KU.table_name='Notes' ORDER BY KU.TABLE_NAME, KU.ORDINAL_POSITION;

Then rename the foreign key:

sp_rename @objname = N'PK_Notes_ADF019271172DFE', @newname = N'PK_Notes'

Update if parameter is not null or empty

Using just IsNull your query would look something like…

UPDATE [Users]
SET FirstName = IsNull(@FirstName, FirstName),
City = IsNull(@City, City)
....
WHERE ...

DECLARE @value AS INT = Null
SELECT CASE WHEN ISNULL(@value, 2)=0 THEN Null Else ISNULL(@value, 2) END

will Update the row with the param value if they are NOT null, otherwise update it to itself aka change nothing.