locked
How to I check if DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges was called? RRS feed

  • Question

  • Hi there,

    Here is my partial code:

    public class MyDbInitializer : DropCreateDatabaseAlways<MyContext>
    {
      {
        protected override void Seed(MyContext myContext)
    ...


    public class MyContext : DbContext
    {
    ...
      public override int SaveChanges()
      {
        //how to I check here if DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges was used?
      }

    Thank you


    Max
    Tuesday, January 24, 2012 12:07 AM

Answers

  • Hi Max,

    Could you please let us know why do you want to check whether it is DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges when SaveChanges is called?

    How about declaring two MyContext classes to represent DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges is used?   e.g.

       public class MyDropCreateDBAlwaysContext : MyContext
       public class MyDropCreateDBIfChanges : MyContext

    Also we can pub all the common logic of our custom context in MyContext class:

       public class MyContext: DbContext. 

    Good day!

    Thanks


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us
    • Marked as answer by Maximusdm Tuesday, January 24, 2012 4:01 PM
    Tuesday, January 24, 2012 3:58 AM

All replies

  • Hi Max,

    Could you please let us know why do you want to check whether it is DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges when SaveChanges is called?

    How about declaring two MyContext classes to represent DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges is used?   e.g.

       public class MyDropCreateDBAlwaysContext : MyContext
       public class MyDropCreateDBIfChanges : MyContext

    Also we can pub all the common logic of our custom context in MyContext class:

       public class MyContext: DbContext. 

    Good day!

    Thanks


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us
    • Marked as answer by Maximusdm Tuesday, January 24, 2012 4:01 PM
    Tuesday, January 24, 2012 3:58 AM
  • Hi Maximusdm;

    In order to set the database initializer strategy you need to execute a statement as one of the following before the first call to the database.

    Database.SetInitializer(new DropCreateDatabaseAlways<YourContextClassName>());

    Or

    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<YourContextClassName>());

    So once you have executed one of the above statements you know which strategy is being used.


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Tuesday, January 24, 2012 3:01 PM