How to use different Entity Framework DbContext in the Area of ASP.NET MVC application?
asp.net-mvc, asp.net-mvc-4, asp.net-mvc-areas, ef-code-first, entity-framework
Solution
Xavier, welcome to code-first!
Yes, code-first was a brilliant approach that promised soooo much. But now you've hit the catch. There's no clever mind at Microsoft (or outside as far as I know) who has come up with a smooth way to alter tables intelligently without endangering the data and possibly schema.
2 Years ago, the implementation strategy was to drop and re-build the DB. That was just intolerable as many of us didn't have SU access and were stopped in our tracks.
For all the advantages I found from code first, I prefer DB first. While data can't be preserved easily, annotations can through buddy classes.
Microsoft has come up with some clever Migration Strategies. I strongly suggest you read both articles. Code Project 2nd:
1) http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx
2) http://www.codeproject.com/Articles/504720/EntityplusFrameworkplusCodeplusFirstplusMigrations
whether you decide to continue with Code-First, they should be enlightening. I sound like a critic but I'm torn between advantages of one and stability of the other.
Finally, I don't think you should preserve 2 dbcontexts. Your POCOs should be consolidated under 1 context.
Problem
Currently I am building a web application with MVC 4 and Entity Framework code first scenario. In the main structure of my application, I have a `Dbcontext(BlogDB)` to manage some `Blog` classes. It works fine as it created all the tables I need in the database. Then I created a Area to host an online store. My idea is to create a separated `DbContext` class(`OnlineStoreDB`) to handle the classes used for Online Store only. My problem is once the `OnlineStoreDB` is fired, entity framework not only created tables for `OnlineStore` BUT ALSO removed old tables. My questions are: - If you know a way to keep the old tables? - How exactly to manage the multi EF context classes in one application? Code: ``` public class BlogDB : DbContext { public BlogDB () : base("DBConnection") { Database.SetInitializer(new BlogInitializer()); } public DbSet<Blog> Blogs { get; set; } public DbSet<Author> Authors { get; set; } public DbSet<Comment> Comments { get; set; } } public class OnlineStoreDB : DbContext { public OnlineStoreDB() : base("DbConnection") { Database.SetInitializer(new OnlineStoreInitializer()); } public DbSet<Order> Orders { get; set; } public DbSet<Product> Products { get; set; } public DbSet<User> Users { get; set; } } ```