Question

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.

Was it helpful?

Solution

Looks like you're forgetting to add the just created Category to the DB table. If you don't add it to the context's table, Entity Framework won't see anything... So you must do something like this:

protected override void Seed(LibraryEntities context)
{
    var categories = new List<Category>
    {
        new Category{Id=1, Name="Sci-fi"}
    };

    foreach(Category c in categories)
    {
        context.Categories.Add(c)
    }

    // Call the Save method in the Context
    context.SaveChanges();  
}

For the DataSource problem, try this modified connection string:

<add name="LibraryEntities"
     connectionString="DataSource=|DataDirectory|R10491_library.sdf"
     providerName="System.Data.SqlServerCe.4.0" />

In one of my projects I have this connection string:

<add name="FitnessCenterContext"
     connectionString="DataSource=|DataDirectory|FitnessCenter.Model.FitnessCenterContext.sdf"
     providerName="System.Data.SqlServerCe.4.0" />

Note above that the database name matches the namespace and Context name.


I also use Application_Start() to call the SetInitializer method in Global.asax.cs file. I see that you're calling it inside Session_Start(). Maybe this is the problem... Change your code to:

protected void Application_Start()
{
     System.Data.Entity.Database.SetInitializer(new R10491.Models.SampleData());
}

You can also try calling the Initialize method:

protected void Application_Start()
{
     System.Data.Entity.Database.SetInitializer(new R10491.Models.SampleData());

     using (var context = new LibraryEntities())
     {
         context.Database.Initialize(true);
     }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top