Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute raw SQL query using Entity Framework without having to use a model?

I am trying to learn C# ASP.NET MVC 5. And I am trying to use Entity Framework for everything I do.

However, I need to run a raw SQL query and return the results into an array.

Here is what I have done so far.

I created my context class which allows me to connect to a server and it also allows me to change the database at run time.

Here is my context class

using ScripterEngine.Models; using System; using System.Collections.Generic; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Core.EntityClient; using System.Data.SqlClient; using System.Linq; using System.Web;  namespace ScripterEngine.DataAccessLayer {     public class BaseContext : DbContext     {         protected string connectionName;         public DbSet<Campaign> Campaign { get; set; }          /**          * Created the connection to the server using the giving connection string name          *           * @param connName          */         public BaseContext(string connName = "BaseConnection")             : base(connName)         {             connectionName = connName;         }          /**          * Changes the default database          *           * @param databaseName          */         public BaseContext setDatabase(string databaseName)         {             var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;              SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);              //change the database before creating the new connection             builder.InitialCatalog = databaseName;              string sqlConnectionString = builder.ConnectionString;              return new BaseContext(sqlConnectionString);         }     } } 

And how to make the connection here is what I do

BaseContext db1 = new BaseContext("server1"); var db1New = db1.setDatabase("someTableName"); string tableName = "SomeTableName";  var results = db1New.Database.SqlQuery("SELECT LOWER(column_name) AS column_name FROM information_schema.columns WHERE table_name = @tableName", tableName).ToArray(); 

This throws an error

The type arguments for method 'System.Data.Entity.Database.SqlQuery(string, params object[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. C:.NET Projects\ScripterEngine\ScripterEngine\Controllers\CampaignController.cs 42 27 ScripterEngine

How can I execute this raw query?

like image 417
Junior Avatar asked Feb 03 '16 18:02

Junior


People also ask

How use raw SQL query in Entity Framework Core?

Entity Framework Core allows you to drop down to raw SQL queries when working with a relational database. Raw SQL queries are useful if the query you want can't be expressed using LINQ. Raw SQL queries are also used if using a LINQ query is resulting in an inefficient SQL query.

How can I directly execute SQL queries in LINQ?

Add a LINQ to SQL class file. Drag and drop the respective table. Now, copy this code in the main method. We are creating an instance of sample datacontext class and then we are using this ExecuteQuery method to execute the SQL query.

Should I use raw SQL or ORM?

ORM is good only for developers and maintenance because most developers aren't very good at SQL, but if you're actually talking about performance, SQL completely trumps it.


1 Answers

Specify string as the type argument.

var results = db1New.Database.SqlQuery<string>("SELECT LOWER(column_name) AS column_name FROM information_schema.columns WHERE table_name = @p0", tableName).ToArray();                                        ^^^^^^ 
like image 151
Mark Cidade Avatar answered Oct 06 '22 00:10

Mark Cidade