Search code examples
c#sql-serverentity-frameworklocaldb

How can I retrieve a list of SQL Server LocalDb names?


I am using Entity Framework with SQL Server LocalDb as a storage medium for my application. I need to find a way to switch between different databases that have the same SQL structure.

My idea is to do this from the DbContext:

public const bool RecreateDB = false;

public UnifiedContext() : this(RecreateDB) { }
public UnifiedContext(bool recreateDb):this(recreateDb, "DemoDB") { }

public UnifiedContext(bool recreateDB, string dbName) : base($"MyUniquePrefix.{dbName}")
{
    if (recreateDB)
        Database.SetInitializer(new DropCreateDatabaseAlways<UnifiedContext>());
    else
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<UnifiedContext, UnifiedConfiguration>());
}

This works fine just like I want it to. However I now need to display a list of LocalDbs for loading I know I can get a list of SQL databases with System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources(); but that doesn't work for LocalDbs.

How can I retrieve a list of LocalDb names?


Solution

  • Since LocalDb is for Developers and not for Database-Administrators, the Databases are stored in a folder.

    Usually this folder is

    C:\Users\User\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB

    Each file ending with .mdf is an DataBase.

    Unfortunately there is - afaik- no built in mechanic to enlist them, since localDb is file based and you are able to save it whereever you want.