0

How do I run a raw query in ASP.NET core to return the row count from a table?

Currently, I am doing this and the returned result is -1. I think the return result is based on the number of records affected.

 int numberOfRows = await
                    appDbContext.Database.ExecuteSqlInterpolatedAsync(
                        $"SELECT CODE FROM [samaster] WHERE CODE={productBrandCode} AND WAREHOUSE={warehouse} ");

Any idea on how to get the count back to numberOfRows variable will be appreciated.

NOTE: The above table is not a model so I need to run a raw query.

Thanks

1
  • Please mark the answer as an accepted if it was helpful or comment it if-else. Commented Apr 16, 2020 at 13:59

4 Answers 4

1

It is currently not possible to get the query result when using ExecuteSqlInterpolatedAsync. The same applies to any additional LINQ Statements.

You can, however, use the underlying ADO.net Provider:

    public IList<IDictionary<string, dynamic>> SelectDynamic(string table)
    {
        using (var command = Database.GetDbConnection().CreateCommand())
        {
            command.CommandText = $"SELECT * FROM [{table}]";
            command.CommandType = CommandType.Text;

            Database.OpenConnection();

            using (var result = command.ExecuteReader())
            {
                var entities = new List<IDictionary<string, dynamic>>();

                while (result.Read())
                {
                    var dict = new Dictionary<string, dynamic>();

                    for (int i = 0; i < result.FieldCount; i++)
                    {
                        dict.Add(result.GetName(i), result.GetValue(i));
                    }

                    entities.Add(dict);
                }

                return entities;
            }
        }
    }

Add this to your DbContext Class and Call it with:

using (var context = new MyDbContext()) // Or get it with DI, depends on your application
{
     var count = context.SelectDynamic("samaster").Where(d => d["CODE"] == productBrandCode && d["WAREHOUSE"] == warehouse).Count();
}

Beware, however, that this is an expensive operation if you have a lot of rows in your table! An alternative approach to only fetch the relevant results would be to replace

command.CommandText = $"SELECT * FROM [{table}]";

with

command.CommandText = $"SELECT CODE FROM [samaster] WHERE CODE={productBrandCode} AND WAREHOUSE={warehouse}";

and pass the parameters as function parameters.

public IList<IDictionary<string, dynamic>> SelectDynamic(string productBrandCode, string warehouse)
    {...

Also make sure to escape all parameters if they are in any way submitted by user input to prevent SQL Injection Attacks!

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I end up using the Command Syntax. Strangely enough, there is nothing built in to do this.
0

There are two common approaches :

A.

int numberOfRows = await appDbContext.Database.ExecuteSqlInterpolatedAsync($"SELECT CODE FROM [samaster] WHERE CODE={productBrandCode} AND WAREHOUSE={warehouse} ").Count();

B.

int numberOfRows = await appDbContext.Database.ExecuteSqlInterpolatedAsync($"SELECT count(*) FROM [samaster] WHERE CODE={productBrandCode} AND WAREHOUSE={warehouse} ").First();

5 Comments

I think you should explicitly point out that this code is only safe from sql injection when the string interpolation is done directly as part of passing the query-parameter to ExecuteSqlInterpolatedAsync. When you interpolate the string before by storing in a separate variable, this code will be vulnerable.
Isn't the above query sql injection safe in the question?
@XAMT I don't have any method called Cout() or First()
@Bikram; Add using System.Linq;
@XAMT I don't know if you tested your code or not. But using System.Linq does not solve the Count method on mine
0

Since nobody gave me the correct answer. I end up using the following.

public async Task<bool> IsAValidProduct(string productBrandCode)
        {
            int count = 0;
            await using DbCommand command = appDbContext.Database.GetDbConnection().CreateCommand();
            command.CommandText =
                "SELECT COUNT(CODE) FROM [samaster] WHERE CODE=@productBrandCode AND WAREHOUSE=@warehouse ";
            command.CommandType = CommandType.Text;
            command.Parameters.Add(new SqlParameter("@productBrandCode", SqlDbType.VarChar)
                {Value = productBrandCode});

            command.Parameters.Add(new SqlParameter("@warehouse", SqlDbType.VarChar)
                {Value = warehouse});
            await appDbContext.Database.OpenConnectionAsync();

            count = (int) await command.ExecuteScalarAsync();

            await appDbContext.Database.CloseConnectionAsync();
            return count == 1;
        }

Comments

0

int c= dbObj.Database.ExecuteSqlRaw(sql); //User this code

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.