Search code examples
c#.netentity-frameworkcode-first

How to access sql file from Seed() in EF?


I have the following:

  string sproc = AppDomain.CurrentDomain.BaseDirectory + "/Stored Procedures/new_message.sql";
  context.Database.ExecuteSqlCommand(sproc);

However the sproc path is invalid for some reason. What is the proper way to access files in your project directory from the Seed Method of EF code-first migrations?

enter image description here


Solution

  • If those .sql files are stored as embedded resources in your assembly, then you can do something like this:

    Assembly asy = Assembly.GetExecutingAssembly();
    
    Stream stm = asy.GetManifestResourceStream("yourAssembly.Stored_Procedures.new_message.sql");
    
    if (stm != null)
    {
        string sql = new StreamReader(stm).ReadToEnd();
        // now you have the SQL statements which you can execute 
        context.Database.ExecuteSqlCommand(sql);
    }
    

    You may use this to determine the name of the resources from Seed() if needed:

    Assembly asy = Assembly.GetExecutingAssembly();
    string[] names = asy.GetManifestResourceNames();
    throw new Exception(string.Join("", names));