/// <summary> /// Attaches a database from MDF, NDF, and LDF files to a new database on the LocalDb SQL Server. /// </summary> /// <param name="databaseFiles">Relative path to database file(s). /// Path is relative to the local of the test assembly DLL, which contains <see cref="TestClassType"/>. /// </param> /// <returns></returns> /// <remarks> /// <para> /// The database is attached to the LocalDb database server. /// </para> /// <para> /// The MDF and LDF (and NDF) files should be added to the Test project. /// Open the file properties from the Solution Explorer and mark the files to Copy to Output Always. /// </para> /// <para> /// You will need to detach the database from the existing SQL Server instance then copy the files to the test project folder. /// You may attach these files to a server right from the test project. /// Then you can make modifications to be included in the test project. /// Be sure to detach the database before committing the changes to source control or running the tests; /// the files need to be detached in order to be safely copied. /// </para> /// </remarks> /// <example> /// <code> /// var attachedDatabase = new LocalDbAttacher(typeof(UnitTest1)) /// .AttachDatabase(@"Databases\MyProduct.mdf", @"Databases\MyProduct_log.ldf"); /// //... /// attachedDatabase.DropDatabase(); /// </code> /// </example> public LocalDbAttacher AttachDatabase(params string[] databaseFiles) { if (databaseFiles == null || databaseFiles.Length < 1) { throw new ArgumentException("At least 1 MDF file must be specified", nameof(databaseFiles)); } var renameMap = databaseFiles .Select(file => AssemblyPath.Combine(file)) .ToDictionary( file => file , file => new FileInfo($"{file.DirectoryName}\\{DatabaseName}_{file.Name}") ); GuardFilesExist(renameMap.Keys); using (var dbMaster = new MasterDbContext()) { dbMaster.DropDatabase(DatabaseName); //Copy the database files foreach (var map in renameMap) { map.Key.CopyTo(map.Value.FullName, overwrite: true); } dbMaster.AttachDatabase(DatabaseName, renameMap.Values.ToArray()); } return(this); }
/// <summary> /// Drop the database from the server. This will implicitly remove the MDF/LDF file copies. /// </summary> public void DropDatabase() { using (var dbMaster = new MasterDbContext()) dbMaster.DropDatabase(DatabaseName); }