JorgeeFG JorgeeFG - 2 months ago 27
ASP.NET (C#) Question

Raw query in ASP.Net Core

I'm coming from a PHP background where you create a PDO Object and can query right away.

I have a database from which I extract data which, for example, is a list of Object -> Quantity (Example Items sales). This is part of another application, I'm just writing an app to show some statistics.

I cannot find how to execute a raw query in ASP.Net Core and have a IEnumerable object. All examples use Entity Framework and a model (which I don't have in my current app, because it's full of raw sql queries).

Answer

You can execute raw SQL like the below (but is prone to injection).

using (var context = new SqlConnection())
{
      var cmd = new SqlCommand
      {
          CommandText = "SELECT * FROM Table",
          CommandType = CommandType.Text,
          Connection = context
      };

      context.Open();

      var reader = cmd.ExecuteReader();

      reader.Close();
  }

I would only do this if you 100% can't use EF and its database/code first techniques.

I updated my answer to ensure that the object is disposed of as soon as it goes out of scope.