fikkatra fikkatra - 1 year ago 67
ASP.NET (C#) Question

Entity Framework migration: access sql file within ASP.NET

I have a ASP.NET Web API project. I'm using Entity Framework Migrations. Currently, I have a custom script that is to be executed during a migration. I'm using the SqlFile method for this:

SqlFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Migrations/Scripts/MyCustomScript.sql"));

This works fine in the integration tests, IF I set the "Copy to Output Directory" of the script to "Copy always".

However, when running the website, the script is copied to
, while
points to the websiteroot. Therefore, an error is thrown stating that the script cannot be found: it resides in the bin folder, not in the root.

How can I load the script so that things work both in the tests and in the actual website?

Answer Source

I would include the script in you dll and than load the script from the dll directly. Than you do not need any if statements and you always know you have the correct scripts included. Set the build action to Embedded resource. Then you can get the script like:

Assembly assembly = Assembly.LoadFile(dll);
using (Stream stream = assembly.GetManifestResourceStream(resourcepath))
using (StreamReader reader = new StreamReader(stream))
    string script = reader.ReadToEnd();