I'm using EntityframeworkCore with a LocalDB-MDF File.
I'm attaching the MDF in the Datacontext
with the following Code.
As you can see, the Code is also found at StackOverflow :)
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// http://stackoverflow.com/questions/3500829/sql-express-connection-string-mdf-file-location-relative-to-application-locatio
var mdfFileFullName = Handlers.DatabaseFileHandler.GetLocalMdfFileFullname();
var connectionString = $@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={mdfFileFullName};Integrated Security=True";
optionsBuilder.UseSqlServer(connectionString);
}
And get the MDF just by definining, that it has to be in the Output-Folder:
internal static class DatabaseFileHandler
{
internal static string GetLocalMdfFileFullname()
{
var mdfFilePath = GetAssemblyPath();
var result = Path.Combine(mdfFilePath, Infrastructure.Constants.DATABASEFILE_NAME);
return result;
}
private static string GetAssemblyPath()
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string result = Uri.UnescapeDataString(uri.Path);
result = Path.GetDirectoryName(result);
return result;
}
}
The MDF-File itself is defined as "Content" and with "Copy if newer".
Now, interesting enough, on some occasions, when I debug my program and stop, on the next startup the MDF is deleted from the Output-Folder.
Unfortunately, I can't even say if the File is deleted when I stop or start the program, since it happens quite rarely.
Interesting enough, this doesn't eve happen, if I clean the solution, so this has to be another Visual Studio mechanism I'm not aware of.