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??

3 Answers 3

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 *...";
}
Sign up to request clarification or add additional context in comments.

Comments

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(); 
    }
}

Comments

0

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

Comments

Your Answer

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