SQL Server Compact 4.0 code-first with connectionstring specified

ef-code-first entity-framework sql-server-ce


I have a simple console application setup and I am trying to get code-first Entity working properly. I've done the basic examples and have set up my classes and context. Once I run my application the database is auto generated and placed in my bin/Debug directory. That's great so at least something works. But now I want to add a SQL Server Compact 4.0 database file (.sdf) to the project and use that instead of the autogenerated database. From what I've read I just need to add a connection string with a name that matches the derived DbContext class.

Below is my app.config:

<?xml version="1.0" encoding="utf-8"?>
    <add name="StudentContext" 
         connectionString="Data Source=Database1.sdf" 
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
        <parameter value="System.Data.SqlServerCe.4.0" />

And this is the error I am receiving when it tries to use the initialize the context.

Visual Studio Error

The inner exception says

Configuration system failed to initialize

I've tried specifying the context directly though the constructor, and still no luck. Hopefully, I am just overlooking something.

(Side note, I grabbed EntityFramework from Nuget and it should be 5.0, yet the appconfig says 4.4? The autogeneration works great so I figured they didnt have anything to do with each other.)

8/16/2013 1:32:22 PM

Accepted Answer

Problem was in my connection string I was pointing to a location that didnt exist. Hence every time I would run the program it would create a file in the bin/debug automatically.

So either specify a direct file path to the sdf file or use |DataDirectory|

connectionString="Data Source=|DataDirectory|Database1.sdf" 

Then peak at what your directory is set to. If its not the directory in your application, then you will need to change this manually. But Websites have an App_Data directory that it should point to.

  var s = AppDomain.CurrentDomain.GetData("DataDirectory");
8/20/2013 1:06:09 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow