1

I am new to C# .Net Entity framework. Appreciate your suggestions. Requirement is to go for code first approach, check if a database exists, if not create the database and tables based on the Model classes and load the tables with data. And this loading should happen only the first time the tables are created. Can you suggest some tutorials for me to go through for the above requirement? I searched the existing questions but couldn't find anything .

Thanks in advance.

Swetha Reddy
  • 61
  • 2
  • 6
  • [Is there a command to check to see if a database exists from Entity Framework](http://stackoverflow.com/questions/13198869/is-there-a-command-to-check-to-see-if-a-database-exists-from-entity-framework) – Divyang Desai Oct 09 '16 at 04:40
  • http://www.entityframeworktutorial.net/code-first/seed-database-in-code-first.aspx you just need to use your strategy CreateDatabaseIfNotExists – jgasiorowski Oct 09 '16 at 07:35

1 Answers1

0

You can try as shown below.

public class MyDBContext: DbContext 
{

    public MyDBContext(): base("YourConnectionString") 
    {
        //This is default initializer
        Database.SetInitializer<MyDBContext>(new CreateDatabaseIfNotExists<MyDBContext>());

    }

    public DbSet<Pet> Pets { get; set; }
    public DbSet<Customer> Customers { get; set; }
}

You can read more about it here : Database Initialization Strategies in Code-First

Sampath
  • 63,341
  • 64
  • 307
  • 441