开发者

How do I recreate DB using EF4 code first for test

开发者 https://www.devze.com 2023-01-27 05:34 出处:网络
I\'m using Entity Framework 4 Code First in my .net MVC 2.0 project and I\'m having hard times to get my DB sync with my Entities. What I want is a page that I can call, as an exemple : /DB/Recreate,

I'm using Entity Framework 4 Code First in my .net MVC 2.0 project and I'm having hard times to get my DB sync with my Entities. What I want is a page that I can call, as an exemple : /DB/Recreate, that would drop my current DB and recreate an empty one. Currently in my global.asax I have

protected override void OnApplicationStarted()
        {
            Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<CorpiqDb>());

            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
            RegisterAllControllersIn(Assembly.GetExecutingAssembly());
        }

I try to switch my database initia开发者_开发问答lizer in my action but I'm realy not sure, since it should already been initialized, that I'm using the right approach :

        Database.SetInitializer(new AlwaysRecreateDatabase<CorpiqDb>());
        var bidon = _session.All<Admin>();
        Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<CorpiqDb>());
        bidon = _session.All<Admin>();

I don'y realy know how to do this, thank you for the help!


Ok I found a solution :

var dbContext = new CorpiqDb().Database ;
dbContext.Delete();
dbContext.Initialize();
dbContext.EnsureInitialized();
Database.SetInitializer(new CreateDatabaseOnlyIfNotExists<CorpiqDb>());

This will drop my database and create a new one that reflect the latest models, I can even seed the database with some data for my test.

0

精彩评论

暂无评论...
验证码 换一张
取 消