2

Recently started trying to dig into code first approach for Entity Framework. I have crated some database tables following various tutorials but none of them did the trick.

Starting from scratch about 3 to 4 times now because the exceptions get more and more absurd. Last time created the database on first access but wasn't able to connect to the database in a second debug session because of missing permissions (using integrated security - wat?). Apparently the .mdf was blocked by System process and only a restart in safe mode allowed me to get rid of it.

Anyway, anew. I have a class library, which contains the database models and a gateway class for external access. I have a Console project to test the database creation and access. EF is installed in the class library via NuGet, reference to EntityFramework.SqlServer.dll is added to the Console project.

The connection string looks like this in both projects:

<connectionStrings>
    <add name="DbConnection"
        connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\LanguageCreator.mdf;Initial Catalog=LanguageCreator;Integrated Security=SSPI"
        providerName="System.Data.SqlClient" />
</connectionStrings>

My context class looks like this:

public class LanguageContext : DbContext {
    public LanguageContext() : base("DbConnection") {
        // Have to set the DataDirectory in code because the wrong one gets set from the config.
        AppDomain.CurrentDomain.SetData("DataDirectory", Directory.GetCurrentDirectory());

        Database.SetInitializer(new CreateDatabaseIfNotExists<LanguageContext>());

        public DbSet<Language> Languages { get; set; }
        public DbSet< ... blablabla various other DbSets following, nothing of interest here.
    }

This is what my gateway looks like:

public class Gateway {
    public void InitializeDatabase() {
        using (LanguageContext context = new LanguageContext()) {
            context.Database.Initialize(true);

            // I did have a configuration class for migration, which seeds some initial data, which is why I'm trying to read the WordTypes here but I left that thing out this time ... will try to add it later on.
            IEnumerable<WordType> wordTypes = context.WordTypes.AsEnumerable();

            List<Language> languages = context.Languages.ToList();
        }
    }
}

The call simply looks like this:

class Program {
    static void Main(string[] args) {
        Gateway databaseGateway = new Gateway();

        databaseGateway.InitializeDatabase();
    }
}

Now, without absolutely anything special, I recieve the following error on starting a debug session:

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: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.

Unfortunately, the Windows Application event log doesn't show any details to that error. Or maybe I'm too stupid to find it ...

What is actually causing this issue and how can I fix this? Everything I found was about access to external SQL Servers but I simply want EF to create an .mdf locally and connect to that.

Ognyan Dimitrov
  • 6,026
  • 1
  • 48
  • 70

2 Answers2

0

I'm very new to Entity Framework and databases in general, but I have a couple suggestions that may help narrow down the issue.

  1. "Verify that the instance name is correct and that SQL Server is configured to allow remote connections." See if the problem is with the server by connecting to it with a different program. If you have trouble connecting to it outside of EF, you can eliminate EF as the problem.

  2. If you can, leave out the connection-string or any mention of your SQL database and see if EF will generate a LocalDB for you. I believe this is the default behaviour of EF. If this works, I think this would also suggest that there's something about your SQL server that's giving you trouble.

Again, I'm very new to this, so just thoughts I'd suggest the way I would try to problem-solve this with my limited knowledge. Hope it's helpful!

Ethan Fischer
  • 1,229
  • 2
  • 18
  • 30
  • As said, I have no SQL Server and thus no connection to it. The database is supposed to be a local .mdf file, which does not yet exist but should be generated on first run. This is not the case, and I'm wondering why. I will try your second suggestion this evening but I doubt it would work. I'm passing the connection string's name to the constructor of DbContext so I assume it'll notify that it cannot find the connection string. Also I wonder where the .mdf would be created, since this is an information in the connection string. – Otto Abnormalverbraucher Oct 29 '15 at 08:05
  • Unfortunately I'm getting the same exception without a connection string – Otto Abnormalverbraucher Nov 01 '15 at 16:48
0

Okay, I figured it out on accident. I installed EntityFramework via NuGet in the Console project and voilá, Visual Studio created the .mdf on starting a debug session.

As it still worked after uninstallation of EntityFramework I created the project anew and checked for differences. I found out that the EntityFramework entries in the app.config were still present, so I copied them over to the new project and now that worked as well.

So if you're stuck with the same problem try adding these parts in the app.config of your console project (or whatever project type you use to access your database class library):

<configSections>
  <section name="entityFramework" 
           type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
           requirePermission="false" />
</configSections>
<connectionStrings>
  <add name="LanguageCreator.data.LanguageCreatorContext"
       connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MyContext.mdf;Integrated Security=SSPI"
       providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="mssqllocaldb" />
    </parameters>
  </defaultConnectionFactory>
  <providers>
    <provider invariantName="System.Data.SqlClient"
              type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
  </providers>
</entityFramework>