0
votes

I am attempting to use code first to generate a database and seed it every time my application is run, however I get the following error:

Cannot attach the file 'C:{filepath}\Application\App_Data\mydatabase.mdf' as database 'mydatabase'.

I've tried to do an 'update-database' (as recommended from other questions) however no .mdf files get generated.

This is the connection string used:

Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\mydatabase.mdf;Initial Catalog=mydatabase;Integrated Security=True

As some background information, I have two different projects which sit in different solutions:

  • Application
  • Domain

The 'application' project has a reference to the 'domain' project

In the domain project I have created my code first models and dbContext:

public class ApplicationContext : IdentityDbContext<User, IntRole, int, IntUserLogin, IntUserRole, IntUserClaim>
{
    public ApplicationContext()
        : base(nameOrConnectionString: "constr") { }

    public ApplicationContext(string connectionString)
        : base(nameOrConnectionString: connectionString) { }

    static ApplicationContext()
    {
        Database.SetInitializer<ApplicationContext>(null);
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Use singular table names
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());

        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = false;
        Configuration.ValidateOnSaveEnabled = false;
    }

    public DbSet<Item> Items { get; set; }
}

public class ApplicationContextInitializer : DropCreateDatabaseAlways<ApplicationContext>
{
    protected override void Seed(ApplicationContext context)
    {

        new List<Item>
        {
          new Item("test")
            {
            },
          new Item("test2")
            {
            },
          new Item("test3")
            {
            }
        }.ForEach(t => context.Items.Add(t));

        base.Seed(context);
    }
}

Inside my application project in the global.asax I have the following :

            Database.SetInitializer(new ApplicationContextInitializer());

I then attempt to add data to the database:

        mUnitOfWork = new UnitOfWork(new RepositoryProvider(new RepositoryFactories()));

        mUnitOfWork.ItemRepository.Add(new Item("my item"));
        mUnitOfWork.Save();
2

2 Answers

0
votes

Turns out you need to add a context to the web.config as follows :

<configuration>
  <entityFramework>
    <contexts>
      <context type="Application.Data.ApplicationContext, Application.Data">
        <databaseInitializer type="Application.Data.ApplicationContextInitializer, Application.Data" />
      </context>
    </contexts>
  </entityFramework>
</configuration>

Useful link if anyone else has a similar problem: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

0
votes

To extend the correct answer, you could also add this by Code:

public class DBConfig
{
    public static readonly DBInitializer Initalizer = new DBInitializer();

    public static void InitalizeDB()
    {
        System.Data.Entity.Database.SetInitializer<DMPDataContext>(Initalizer);
    }
}
protected void Application_Start()
    {
        //common application startups
        DBConfig.InitalizeDB();
        //...           
    }