Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a command to check to see if a database exists from Entity Framework?

I may have worded the question poorly but in my global.asx file i use

 if (System.Diagnostics.Debugger.IsAttached)
        {
            var test = new TestDbSeeder(App_Start.NinjectWebCommon.UcxDbContext);
            test.seed();
       }

This checks to see if the debugger is attached and runs my test seeder so that my acceptance tests always pass.

I need to check to see if the database exists as well and if not run this code first:

  var test2 = new DataSeeder();
  test2.Seed(App_Start.NinjectWebCommon.UcxDbContext);

This dataseeder is the actual data that has to always be in the database. Is there a command to check if the database exists so that I can run that code block. Thanks!

like image 638
Robert Avatar asked Nov 02 '12 16:11

Robert


2 Answers

Will the Database.Exists method work for you?

if (!dbContext.Database.Exists())
    dbContext.Database.Create();

Edit #1 to answer comment

public class DatabaseBootstrapper
{
    private readonly MyContext context;

    public DatabaseBootstrapper(MyContext context)
    {
        this.context = context;
    }

    public void Configure()
    {
        if (context.Database.Exists())
            return;

        context.Database.Create();
        var seeder = new Seeder(context);
        seeder.SeedDatabase();
    }
}

That should do exactly what you want. In your global.asax file...

public void Application_Start()
{
    var context = ...; // get your context somehow.
    new DatabaseBootstrapper(context).Configure();
}
like image 64
Jarrett Meyer Avatar answered Sep 22 '22 05:09

Jarrett Meyer


In Entity Framework Core it works like this:

namespace Database
{
    using Microsoft.EntityFrameworkCore.Infrastructure;
    using Microsoft.EntityFrameworkCore.Storage;

    public partial class MyContextClass
    {
        /// <summary>
        /// Checks if database exists
        /// </summary>
        /// <returns></returns>
        public bool Exists()
        {
            return (this.Database.GetService<IDatabaseCreator>() as RelationalDatabaseCreator).Exists();
        }
    }
}

Make sure the class name equals your database Context class name and is in the same namespace.

Use it like this:

var dbExists = (MyContextClass)db.Exists()

Source: StackOverflow Answer

like image 22
CodingYourLife Avatar answered Sep 19 '22 05:09

CodingYourLife