fikkatra
fikkatra

Reputation: 5822

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 <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?

Upvotes: 0

Views: 230

Answers (2)

Peter
Peter

Reputation: 27944

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();

Upvotes: 2

Matthias Burger
Matthias Burger

Reputation: 5946

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";

Upvotes: 1

Related Questions