I have problem with initializing data into SQL Server Compact .sdf data file in .NET web application.
I have a data initialization class.
namespace R10491.Models
{
public class SampleData : DropCreateDatabaseAlways<LibraryEntities>
{
protected override void Seed(LibraryEntities context)
{
var categories = new List<Category>
{
new Category{Id=1, Name="Sci-fi"}
};
}
}
}
(for testing purposes I use DropCreateDatabaseAlways instead of DropCreateDatabaseIfModelChanges)
This initializer class I call in the Global.asax.cs file:
protected void Session_Start()
{
System.Data.Entity.Database.SetInitializer(new R10491.Models.SampleData());
}
(again for testing purposes I call it on every session start).
My connection string definition:
<connectionStrings>
<add name="LibraryEntities"
connectionString="Data Source=C:\Users\Administrator\Documents\Visual Studio 2012\Projects\2OBOP3_KU1\R10491\App_Data\R10491_library.sdf;"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
But the initialization doesn’t work – tables defined in SampleData class are not created nor data are initialized.
Looks like you’re forgetting to add the just created
Categoryto the DB table. If you don’t add it to thecontext‘s table,Entity Frameworkwon’t see anything… So you must do something like this:For the DataSource problem, try this modified connection string:
In one of my projects I have this connection string:
Note above that the database name matches the namespace and Context name.
I also use
Application_Start()to call theSetInitializermethod inGlobal.asax.csfile. I see that you’re calling it insideSession_Start(). Maybe this is the problem… Change your code to:You can also try calling the
Initializemethod: