0

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 <websiteroot>\bin\Migrations\MyCustomScript.sql, while AppDomain.CurrentDomain.BaseDirectory 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?

2 Answers 2

2
+50

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

2 Comments

I've made it into this: Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName) and closed the brackets, but otherwise: good solution!
Nice, it depends on where you have embedded the files. Good that this helps you!
1

I would fix it this way (it's not the best way, but it's a way)

string sqlfilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Migrations/Scripts/MyCustomScript.sql");
if (!File.Exists(sqlfilepath))
    sqlfilepath = "your other path where it might exist";

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.