1

In Entity Framework Code first i want to check database is exist before create Database. In code first when i call Entities dc = new Entities() then it goes to OnModelCreating and generate Database. How can i check if the Database exists in Entity framework Code first?

SheetJS
  • 22,470
  • 12
  • 65
  • 75
Joby James
  • 429
  • 8
  • 22
  • check this http://stackoverflow.com/a/13198899/87956 – Vinay Pandey Nov 12 '13 at 04:40
  • possible duplicate of [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) – Gert Arnold Nov 12 '13 at 06:53

2 Answers2

3

You can do:

using(var dbContext = new MyContext())
{
    if (!dbContext.Database.Exists())
        dbContext.Database.Create();
}

Edit:

Following the colegue sugestion, the meaning of this code is very simple: Supose your context constructor is not set to create the database, so before sending any database operations, you can check if it exists, if not, you can create a new one with the connection string parameters being the rules for the creation.

Mortalzera
  • 96
  • 9
  • Even if your comment might be correct, adding a little explaination of what does your solution do and why it works in tue OP's context, won't harm and will encourage other users to upvote your answer. – nKn Feb 13 '14 at 19:21
  • I could not care less about upvoting, but you are right, a little explanation could help the others = ]. – Mortalzera Feb 14 '14 at 16:53
0

This would be a static alternative, that works even without creating the DbContext first:

    System.Data.Entity.Database.Exists(dbNameOrconnectionString);
Whopperle
  • 81
  • 1
  • 4