0

I'm trying to extend the Asp.NET MVC framework so I can make modules. I want to be able to make separate mini mvc-projects, combine them in the mvc-app and build/install the whole thing. This way I can select the desired modules into one application.

To make the mini MVC projects I want to use this method: http://www.wynia.org/wordpress/2008/12/aspnet-mvc-plugins/

For now I'm trying to make the database build with multiple dbcontexts. I used the IRepository pattern to achieve that. First I made a Entity Framework (4.3) project with this pattern and was able to make a complete database with the OnModelCreating event.

public class Context : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //    /* Use MEF to load all plugins. I'll use the mock interface IPlugin */

            List<IContext> Contexts = new List<IContext>();
            Contexts.Add(new BikeContext());
            Contexts.Add(new CarContext());
            Contexts.Equals(new BlogContext());


            foreach (IContext context in Contexts)
                context.Setup(modelBuilder);
        }   
    }

this is an example function that runs the Setup and is in every subcontext:

public class CarContext : Context, IContext
    {
        public List<Car> Cars { get; set; }

        void IContext.Setup(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Car>().ToTable("Cars");
            modelBuilder.Entity<Car>().HasKey(car => car.Id);               
        }
    }

This repository is from the example given in MEF Plugins and EF CodeFirst - How?

If I use this in a mvc application (which uses the EF on default, right?) the OnModelCreating function does run, so do the setup functions, but it creates neither the database nor the tables. In the end I get an error because the app can't make a connection to the database when it tries to select data. Which is logical because there's no database.

What I basically want is to use the mef-plugins-and-ef-codefirst solution in a MVC app. Am I missing something? Is there another way to create tables manually in your code in MVC/EF?

Community
  • 1
  • 1
Willem de Jong
  • 905
  • 2
  • 15
  • 31

1 Answers1

0

Well I found the solution myself:

I added this to the index of a controller:

Context context = new Context();
            context.Database.CreateIfNotExists();

And changed the public List in the CarContext into public DbSet.

It makes the database with the tables now, and I get the data through CarContext.

Willem de Jong
  • 905
  • 2
  • 15
  • 31