2

I have a complex query which can grow or get smaller depending on which paramaters it receives. Example:

public string CreateQuery(string[]  fields)
{
    var query = "SELECT student_name,student_last_name FROM students";

    if(fields[0]!= "")
    {
        query += " WHERE studient_id='"+fields[0]+"'";
    }

    if(fields[1] != null)
    {
        //them....
    }
    //and so on

    return query;
}

So i need to execute that query like webmatrix

ViewBag.StudentInf = db.Query("Query string here...");

How, then, can I execute a query string with entity Framework??

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86

3 Answers3

1

For .NET Framework version 4 and above: use ObjectContext.ExecuteStoreCommand()

A tutorial here

Or try this function

static void ExecuteSql(ObjectContext c, string sql)
{
    var entityConnection = (System.Data.EntityClient.EntityConnection)c.Connection;
    DbConnection conn = entityConnection.StoreConnection;    
    ConnectionState initialState = conn.State;

    try
    {
        if (initialState != ConnectionState.Open)
            conn.Open();  

        using (DbCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
        }
    }
    finally
    {
        if (initialState != ConnectionState.Open)
            conn.Close(); 
    }
}
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
KF2
  • 9,887
  • 8
  • 44
  • 77
1

You really should not be doing this. Your running a very big risk of someone performing a SQL injection attack on you.

You can do something like recommended in this answer.

But if you really want to do it you can do the following:

using (System.Data.Common.DbCommand cmd = db.Database.Connection.CreateCommand())
{
    cmd.CommandText = "SELECT *...";
}
Community
  • 1
  • 1
pingoo
  • 2,074
  • 14
  • 17
0

if your question is about building a dynamic query with Linq to Entities you can, at least, use Dynamic Linq.

tschmit007
  • 7,559
  • 2
  • 35
  • 43