EF执行原生sql参数化查询,DbCommand参数化查询

目录

    • 方式一(返回单值):
    • 跟踪EF生成的sql
    • 方式二,EF Core(返回列表,参数配置):
    • AUAP_DbContext

方式一(返回单值):

  public async Task<ActionResult> SaveLockConfig(Password_error_lock_config config)
        {
            if (config == null)
            {
                return Json(new ResultInfo() { Result = false, Messages = "config不可为空" });
            }
            using (InfoReportSystemDBEntities db = new InfoReportSystemDBEntities())
            {
                int count = await db.Database.ExecuteSqlCommandAsync("update [password_error_lock_config] set [password_max_error_count]={0},[lock_minutes]={1},[Time_limit_seconds]={2},[remark]={3},[update_password_days]={4} where id={5} "
                    , new object[] { config.Password_max_error_count,
                        config.Lock_minutes,
                        config.Time_limit_seconds,
                        config.Remark,
                        config.Update_password_days,
                        config.Id });            
                if (count > 0)
                {
                    return Json(new ResultInfo() { Result = true, Messages = "保存成功" });
                }
            }
            return Json(new ResultInfo() { Result = false, Messages = "保存失败" });
        }

跟踪EF生成的sql

----------ef生成的sql 开始--------
Opened connection asynchronously at 2021/4/20 10:48:07 +08:00

----------ef生成的sql 开始--------
Started transaction at 2021/4/20 10:48:07 +08:00

----------ef生成的sql 开始--------
update [password_error_lock_config] set [password_max_error_count]=@p0,[lock_minutes]=@p1,[Time_limit_seconds]=@p2,[remark]=@p3,[update_password_days]=@p4 where id=@p5 
----------ef生成的sql 开始--------


----------ef生成的sql 开始--------
-- p0: '6' (Type = Int32, IsNullable = false)

----------ef生成的sql 开始--------
-- p1: '59' (Type = Int32, IsNullable = false)

----------ef生成的sql 开始--------
-- p2: '300' (Type = Int32, IsNullable = false)

----------ef生成的sql 开始--------
-- p3: '管理员配置' (Type = String, IsNullable = false, Size = 5)

----------ef生成的sql 开始--------
-- p4: '90' (Type = Int32, IsNullable = false)

----------ef生成的sql 开始--------
-- p5: '0cf7d494a86847a3bbb5436576f72c97' (Type = String, IsNullable = false, Size = 32)

----------ef生成的sql 开始--------
-- Executing asynchronously at 2021/4/20 10:48:07 +08:00

Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.RemoteDependency","time":"2021-04-20T02:48:07.3227544Z","tags":{"ai.internal.sdkVersion":"rddf: 2.0.0.25000","ai.device.roleInstance":"DESKTOP-ACRFQSI","ai.operation.name":"POST Configure/SaveLockConfig","ai.operation.parentId":"dl1eIMYSMlM=","ai.operation.id":"dl1eIMYSMlM="},"data":{"baseType":"RemoteDependencyData","baseData":{"ver":2,"name":". | snqk_information_sc3","id":"Oy63uHzMgvA=","value":1.6191,"dependencyKind":0,"success":true,"properties":{"DeveloperMode":"true"}}}}
----------ef生成的sql 开始--------
-- Completed in 3 ms with result: 1

----------ef生成的sql 开始--------


----------ef生成的sql 开始--------
Committed transaction at 2021/4/20 10:48:07 +08:00

----------ef生成的sql 开始--------
Closed connection at 2021/4/20 10:48:07 +08:00

Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Request","time":"2021-04-20T02:48:07.2261105Z","tags":{"ai.operation.id":"dl1eIMYSMlM=","ai.internal.sdkVersion":"web: 2.0.0.25000","ai.device.roleInstance":"DESKTOP-ACRFQSI","ai.operation.name":"POST Configure/SaveLockConfig"},"data":{"baseType":"RequestData","baseData":{"ver":2,"id":"dl1eIMYSMlM=","name":"POST Configure/SaveLockConfig","startTime":"2021-04-20T10:48:07.2261105+08:00","duration":"00:00:00.1282990","success":true,"responseCode":"200","url":"http://localhost:5117/Configure/SaveLockConfig","httpMethod":"POST","properties":{"DeveloperMode":"true"}}}}
线程 0x7714 已退出,返回值为 0 (0x0)。
程序“[6088] iisexpress.exe: 程序跟踪”已退出,返回值为 0 (0x0)。
程序“[6088] iisexpress.exe”已退出,返回值为 -1 (0xffffffff)

方式二,EF Core(返回列表,参数配置):

EF Core参数化查询,原始sql

/// 
/// / 读取auap表字段列表
/// 
/// 表名
/// 数据库名
/// 
public async Task<List<ColumnView>> GetAuapTableColumnList(string table, string database=null)
{
	if (string.IsNullOrWhiteSpace(table))
	{
		return null;
	}

	List<ColumnView> columns = new List<ColumnView>();

	string sql = $@"   
SELECT major_id, minor_id, t.name AS 'table_name', c.name AS 'column_name', value AS 'comment'
FROM sys.extended_properties AS ep
INNER JOIN sys.tables AS t ON ep.major_id = t.object_id
INNER JOIN sys.columns AS c ON ep.major_id = c.object_id AND ep.minor_id = c.column_id
WHERE class = 1 and t.name=@table  ";

	System.Data.Common.DbConnection dbConnection = null;
	try
	{
		AUAP_DbContext aUAP_DbContext = new AUAP_DbContext();
		dbConnection = aUAP_DbContext.Database.GetDbConnection();
		await dbConnection.OpenAsync();
		DbCommand dbCommand = dbConnection.CreateCommand();
		dbCommand.CommandText = sql;

		DbParameter parame1 = dbCommand.CreateParameter();
		parame1.ParameterName = "@table";
		parame1.Value = table;
		dbCommand.Parameters.Add(parame1);

		//DbParameter parame2 = dbCommand.CreateParameter();
		//parame2.ParameterName = "@data02";
		//parame2.Value = database;
		//dbCommand.Parameters.Add(parame2);

		DbDataReader reader = await dbCommand.ExecuteReaderAsync();
		while (await reader.ReadAsync())
		{
			ColumnView columnView = new ColumnView();
			columnView.Table_name = Convert.ToString(reader["table_name"]);
			columnView.Column_name = Convert.ToString(reader["column_name"]);
			columnView.Comment = Convert.ToString(reader["comment"]);
			columns.Add(columnView);
		}
		await reader.CloseAsync();
		await reader.DisposeAsync();
		await dbCommand.DisposeAsync();
	}
	catch (Exception ex)
	{
		exception_LogDal.AddExceptionLog(ex);
	}
	finally
	{
		if (dbConnection != null)
		{
			if (dbConnection.State == System.Data.ConnectionState.Open)
			{
				await dbConnection.CloseAsync();
				await dbConnection.DisposeAsync();
			}
		}
	}
	return columns;
}

AUAP_DbContext

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebInfoFormReport.Model;

namespace WebInfoFormReport.DataImpl
{
    public class AUAP_DbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string connectionString = MyConfigReader.GetConfigValue("AUAP_connctionDb");
            optionsBuilder.UseSqlServer(connectionString);

            //设置不跟踪所有查询  
            optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);


#if DEBUG
            //启用敏感数据日志记录
            optionsBuilder.EnableSensitiveDataLogging();

            //记录日志          
            optionsBuilder.LogTo(msg =>
            {
                //调试-窗口消息
                System.Diagnostics.Debug.WriteLine(msg);
                //输出-窗口消息
                //Console.WriteLine(msg);
                //LogHelpter.AddLog(msg);
            });
#endif
        }
    }
}

你可能感兴趣的:(EF,EF,Core,EF,c#)