Search code examples
c#entity-frameworkcode-first

Getting an error when trying to access or create Entity Framework code first local file on a different computer


I have been struggling with this problem for the last couple of days now, I tried various connection strings and never managed to get it to work. I have a C# application where I use Entity Framework to create a local db file

public class MyDBContext : DbContext
{
    private readonly static MyDBContext _dbcontext = new MyDBContext();

    public static MyDBContext getDBContext()
    {
        return _dbcontext;
    }

    private MyDBContext () : base(@"Data Source=(LocalDB)\v11.0;Initial Catalog=mydb;Integrated Security=True") {
            //Database.Initialize(true); <-- I also tried commenting and leaving this
    }
}

So this really works fine in VS and it creates the mydb file in user folder. I also tried putting the AttachDbFilename=|DataDirectory|mydb.mdf; insted of Initial Catalog=mydb; this also works and reads the file next to the application. But once I copy the exe (and necessary DLLs) to another PC or VM, I get the following error at the constructor in all cases:

System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)


Solution

  • You can install SQL express, LocalDB is an option (not selected by default IIRC), or there is a standalone LocalDB installer here