Linq DataContext.Log - logging sql command with pa

2019-08-29 19:06发布

问题:

I using Linq DataContext.Log and I want to save sql command with parameters. how may I do this??

Now to log is writing:

SELECT [t0].[Id_User],
[t0].[FirstName], [t0].[LastName],
[t0].[UserName], [t0].[Password],
[t0].[District_Id], [t0].[Active],
[t0].[MobileDevice_Id],
[t0].[IsMobile], [t0].[IsWWW],
[t0].[IsWholesaler], [t0].[Acc_Admin],
[t0].[Warehouse_Id], [t0].[PIN],
[t0].[ValidFrom], [t0].[ValidTo],
[t0].[IsExternal], [t0].[UserType],
[t0].[DefaultDepartment_Id],
[t0].[Code], [t0].[RowsOnPage],
[t0].[ClientGroup_Id],
[t0].[ClientGroup2_Id],
[t0].[ServerHash],
[t0].[CanOrderInPacks], [t0].[Email],
[t0].[IsAdmin],
[t0].[HasAccessToAllInferiorsData],
[t0].[IsSupplier], [t0].[Position],
[t0].[syncstamp] AS [Syncstamp],
[t0].[Source], [t0].[Deleted],
[t0].[DefaultClient_Id] FROM
[dbo].[Users] AS [t0] WHERE
([t0].[UserName] = @p0) AND
([t0].[Deleted] = @p1)

I want write @p0 and @p1 to log

回答1:

Param value can be read by following line of code

var results = db.calltodatabase.Where(pradicate); 
IQueryable query = results;

    DbCommand dbCommand = dataContext.GetCommand(query);


        var result = new SqlQueryText();


        result.Text = dbCommand.CommandText;
        int nParams = dbCommand.Parameters.Count;
        result.Params = new ParameterText[nParams];
        for (int j = 0; j < nParams; j++)
        {
            var param = new ParameterText();
            DbParameter pInfo = dbCommand.Parameters[j];
            param.Name = pInfo.ParameterName;
            param.SqlType = pInfo.DbType.ToString();
            object paramValue = pInfo.Value;
            if (paramValue == null)
            {
                param.Value = null;
            }
            else
            {
                param.Value = pInfo.Value.ToString();
            }
            result.Params[j] = param;
        }


标签: linq-to-sql