C# MySQL EF 6 Code First Migrations Create Custom Stored procedure with dynamic where clause prepare statement gives error
<p>I'm using MySql 5.5 database. I have created my database using Entity Framework code first migrations and created default stored procedures for Insert Update and delete operations using the MapToStoredProcedures() method in DBContext class. I'm trying to add a custom migration class. Code snippet below:</p>

<pre><code>using System;
using System.Data.Entity.Migrations;

public partial class Views : DbMigration
{
    public override void Up()
    {
        Sql(@"
            CREATE VIEW View_Jobs
            AS 
            select 
            job.JobId as JobId,
            job.JobNo as JobNo,
            ....";
        );

        CreateStoredProcedure(
           "dbo.GetOpenJobs",
           p =&gt; new
           {
               UserId = p.Long(),
               RoleId = p.Long()
           },
           body:
            @"
            DECLARE query varchar(1000);
            DECLARE strWhere varchar(100);

            set @query = 'select JobId, JobNo, ... from view_jobs  ';

            IF RoleId &lt;&gt; 1 THEN
                set @query = concat(@query, ' WHERE AssignedTo = ', UserId, ' AND AssignedToRole = ', RoleId, ' ');  
            end if;

            set @query = concat(@query, ' group by JobId, JobNo,... ');

            select @query;

            PREPARE stmt FROM @query;
            EXECUTE stmt;
            DEALLOCATE PREPARE stmt;"
        );
    }

    public override void Down()
    {
        DropStoredProcedure("dbo.GetOpenJobs");
        Sql(@"DROP VIEW IF EXISTS view_jobs;");
    }
}
</code></pre>

<p>When i use Update-Database command, the view is getting created properly in database but for creating stored procedure i'm receiving below error. </p>

<pre><code>"You have an error in your SQL syntax; check the manual that corresponds to     your MySQL server version for the right syntax to use near 'query;
            EXECUTE stmt;
            DEALLOCATE PREPARE stmt;
 END' at line 19"
</code></pre>

<p>The same stored proc is working fine in the database. 
Even though i have mentioned @query in my .NET code, while updating database it is considering as query without @ symbol. </p>

<p>Here is one work around of creating them in seed method. But i dont prefer this. 
<a href="https://stackoverflow.com/questions/7667630/can-you-create-sql-views-stored-procedure-using-entity-framework-4-1-code-firs">Can you create sql views / stored procedure using Entity Framework 4.1 Code first approach</a> </p>

<p>Does anyone know how to resolve this or any work around available apart from the above link shared?</p>