Search code examples
sql-server-2008asp.net-mvc-4elmah.mvc

Create elmah table and stored procedures when application starts


I'm able to create the elmah table and stored procedures using the script:

https://code.google.com/p/elmah/downloads/list

Using the SQL Server Management Studio. And it woks fine.

But I would like to be able to create that table and stored procedures from the code. Where and how should I do that?


Solution

  • As I'm using Entity Framwork Migrations, I'm runing it from the Up() method in my inicial migration (Downloaded ELMAH-1.2-db-SQLServer.sql file):

     public override void Up()
     {
            string[] ElmahCommands = GetElmahStructureScript();
            foreach (string line in ElmahCommands)
            {
                Sql(line);
            }
            //...
    }
    
    public static string[] GetElmahStructureScript()
    {
            string sqlConnectionString = new MyDbContext().Database.Connection.ConnectionString;
            Regex regex = new Regex("^GO", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            string[] lines = regex.Split(ElmahScript);
            return lines;
    }
    
    static string ElmahScript = @"
    CREATE TABLE [dbo].[ELMAH_Error] ...
    ...
    SET QUOTED_IDENTIFIER OFF 
    GO
    SET ANSI_NULLS ON";
    

    Atention: Remove the last "GO" statement! (I also removed the first part of the script, to check the compatibility version...)