Domanda

Currently I have a nice model, and I can generate a database based on that, but from what I can tell, the tables are never created (leading to all sorts of fun runtime errors).

My understanding is that there are three options for code first that would force EF to create the tables for me:

  • DropCreateDatabaseAlways
  • CreateDatabaseIfNotExists
  • DropCreateDatabaseIfModelChanges

How can I use these if I am doing things model first?

Additionally, is this an expected error, or when I selected generate database from model the first time is this supposed to happen automatically?

Edit: I tried calling

            context.Database.Initialize(true);
            context.Database.CreateIfNotExists();

and nothing changes.

È stato utile?

Soluzione

also this is good toturial tutorial

but if you made the model good the first time you access the dbContext the db should be created by the db strategy which you can set: Database.SetInitializer() set initializer

in short after you create your model you need to create class that inherit from DbContext:

 public class CompanyContext : DbContext
{
    public CompanyContext() : base("CompanyDatabase") { }

    public DbSet<Collaborator> Collaborators { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<Manager> Managers { get; set; }
}

and then when you access this context the tables should be generated. you can also seed the database with data you should inherit from the strategy you want to implement look at this link seeding database

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top