Search code examples
c#asp.net-coreaspnetboilerplate

Aspnetboilerplate: How to execute raw sql query




How to execute raw sql query in asp.net core aspnetboilerplate 5.6.0,
It seems entity framework code 3.1.4 is referred in the project

My code is as follows

public interface ISqlExecuter
{
    int Execute(string sql, params object[] parameters);
}

public class SqlExecuter : ISqlExecuter, ITransientDependency
{
    private readonly IDbContextProvider<InsProDbContext> _dbContextProvider;

    public SqlExecuter(IDbContextProvider<InsProDbContext> dbContextProvider)
    {
        _dbContextProvider = dbContextProvider;
    }

    public int Execute(string sql, params object[] parameters)
    {
        _dbContextProvider.GetDbContext().Database//<= Here I dont see any function to execute SQL query
        //return 0;
        //return _dbContextProvider.GetDbContext().Database.ExecuteSqlCommand(sql, parameters);
    }
}

Solution

  • They have provided the extension method ExecuteSqlRaw, you can call this method to run the query.

    You can call like this.

    dbContextProvider.GetDbContext().Database.ExecuteSqlRaw();
    dbContextProvider.GetDbContext().Database.ExecuteSqlRawAsync();