kiwijus kiwijus - 1 year ago 124
C# Question

Code First database generation external dll

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

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:

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()
protected override void OnModelCreating(DbModelBuilder modelBuilder)
// Use singular table names



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));


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"));

Answer Source

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

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

Useful link if anyone else has a similar problem:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download