EF core 学习 执行原生sql语句 之ExecuteReader 和ExecuteScalar
通过ef core 源码分析 Microsoft.EntityFrameworkCore.Storage.RelationalCommandExtensions类中有相应的方法 为此得到相应的结果:
为此在我们的数据上下文中拓展方法:
public async Task<DbDataReader> ExecuteReaderAsync(RawSqlString sql, params object[] parameters) { using (await Database.GetService<IConcurrencyDetector>().EnterCriticalSectionAsync(default)) { RawSqlCommand rawSqlCommand = Database.GetService<IRawSqlCommandBuilder>().Build(sql.Format, parameters); return (await rawSqlCommand.RelationalCommand.ExecuteReaderAsync(Database.GetService<IRelationalConnection>(), rawSqlCommand.ParameterValues)).DbDataReader; } } // FormattableString public Task<DbDataReader> ExecuteReaderAsync(FormattableString sql) { return ExecuteReaderAsync(sql.Format, sql.GetArguments()); } public Task<object> ExecuteScalarAsync(FormattableString sql) { return ExecuteScalarAsync(sql.Format, sql.GetArguments()); } public async Task<object> ExecuteScalarAsync(RawSqlString sql, params object[] parameters) { using (await Database.GetService<IConcurrencyDetector>().EnterCriticalSectionAsync(default)) { RawSqlCommand rawSqlCommand = Database.GetService<IRawSqlCommandBuilder>().Build(sql.Format, parameters); return await rawSqlCommand.RelationalCommand.ExecuteScalarAsync(Database.GetService<IRelationalConnection>(), rawSqlCommand.ParameterValues); } }