3

I tried to use EF6 and MySQL. I am sure the my connection to the database is working because the preferred database schema exists. However, only the __migration table exists.

I have the following codes

My Model

[Table("my_model")]
public class ModelA
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ModelAId { get; set; }

    public string ModelAProperty { get; set; }
}

My DBContext

public class ModelAContext : DbContext
{
    public ModelAContext() : base("DefaultConnection")
    {

    }

    static ModelAContext()
    {
        Database.SetInitializer( new DropCreateDatabaseIfModelChanges<ModelAContext>());
    }

    public DbSet<ModelA> MyModels { get; set; } 
}

My Initializer

// Assuming this is run during the application initialization
    public static void InitializeDB()
    {
        using (var context = new ModelAContext())
        {
            if (!context.Database.Exists())
            {
                // Create the SimpleMembership database without Entity Framework migration schema
                ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
            }
            context.Database.CreateIfNotExists();
        }
    }

The corresponding table for ModelA was not created. I always get a MySQL exception where a table (in this case app.my_model) does not exists.

Any help will be much appreciated.

P.S. If you have any good tutorial where I can setup my MySQL and EF6 in ASP.NET MVC4, it would be great. As of now, I can't seem to use the WebSecurity helper of MVC4.

edmandie
  • 71
  • 1
  • 4
  • In regards to setting up EF6 and MySQL together, here's some notes of the research I did some months ago, hope it helps - http://stackoverflow.com/questions/20277677/dynamic-mysql-database-connection-for-entity-framework-6/20294903#20294903 – francisco.preller Feb 13 '14 at 12:59
  • @francisco.preller, thanks for the response. I actually have read your answer from that link. I already got the MySQL and EF6 to work but the tables for the models are not created automatically. It seems that context.Database.CreateIfNotExists() only create the database/schema and not the tables. Base on my research, they say that I need to create a query to the DbSet to initialize the table but, again, I always get the error where the table does not exists. – edmandie Feb 13 '14 at 13:15

1 Answers1

1

In your Global.ascx ad

  AppDbContext db = new AppDbContext();
            db.Database.Initialize(true);
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59