Multiple DbContexts in multiple assemblys with code first RRS feed

  • Question

  • Hello,

    I'm using CodeFirst and I've got a big project with many different DbContexts, accessing different parts of the database. Some contexts also remain in other assemblies as the project must be dynamically extensible.

    Now when I access the database with the different contexts, I get an error, that the database metadata does not correspond to the model. There is one table EdmMetadata that contains one hash value of a model, but I've got more than one model, because I've got more than one DbContext. So the different DbContexts conflict. Am I missing something, or is it not possible to have multiple DbContexts?


    Here is a small test application that fails to access the database with two different DbContexts in the same assembly:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.Entity;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.ComponentModel.DataAnnotations;
    namespace ConsoleApplication1 {
    	public class Table1 {
    		public int ID { get; set; }
    		public string Text { get; set; }
    	public class Table2 {
    		public int ID { get; set; }
    		public string Text { get; set; }
    	class Program {
    		public class Context1: DbContext {
    			public Context1(DbConnection db) : base(db, true) { }
    			public DbSet<Table1> Table1 {get; set;}
    		public class Context2: DbContext {
    			public Context2(DbConnection db) : base(db, true) { }
    			public DbSet<Table2> Table2 { get; set; }
    		static void Main(string[] args) {
    			//Database.SetInitializer<DbContext>(new DropCreateDatabaseIfModelChanges<Context1>());
    			Database.SetInitializer<Context1>(new DropCreateDatabaseIfModelChanges<Context1>());
    			Database.SetInitializer<Context2>(new DropCreateDatabaseIfModelChanges<Context2>());
    			var con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|test4.mdf;Initial Catalog=test5;Integrated Security=True;User Instance=True");
    			using (var c = new Context1(con)) {
    				var e = new Table1 { Text = "hallo 1" };
    				//c.Database.ExecuteSqlCommand("CREATE TABLE Table2 (ID int IDENTITY(1,1) PRIMARY KEY, Text nvarchar(MAX));");
    			con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|test4.mdf;Initial Catalog=test5;Integrated Security=True;User Instance=True");
    			using (var c = new Context2(con)) {
    				var e = new Table2 { Text = "hallo 2" };

    Thursday, July 21, 2011 1:14 AM


All replies

  • there are many articles talked about multiple DbContext

    Additonally, you should tell us more error information and maybe the questoin solved better.

    Hope this helps.


    Just a newbie for everything.
    Saturday, July 23, 2011 2:35 PM
  • Hi folks,


    Well, I think the main point from simon is valid. The question is simply - how can I use more than one instances of "DbContext" in one Application. As Simon pointed out there is no built in strategy for using 'Database Migrations' based upon multiple Database Contextes. And this is as far as I know a limitation which is already true. Right?

    If anyone knows a workaround or best practices here I would like to know.

    Question 2: Folks, do you really use one DbContext in EF 4.1x Code First approach with a significant number of tables and/or relations? If so, please tell me how :)

    Have a great day/week/year/life (depends on the date you answer...)! Günther

    Wednesday, November 2, 2011 4:38 PM
  • Hi,

    I've implemented a library that works around the problem, but it's a big library that also implements other cool stuff, and the database code unfortunately is a bit tied to other stuff in the library, because everything is extensible, so I cannot just publish the database part. The library is meant for an ASP.NET CMS. Nevertheless it is possible to use the library without using all the other stuff, also in an non ASP.NET environment. The library is OpenSource and on CodePlex here. It is not yet finished, when it is finished it will also support editable content in an website. The sourcecode consists of many projects extending the basic library, but the database part is in the basic library Silversite.Core.dll.

    What the library does is implement a new Context class and  an IDatabaseInitializer. The IDatabaseInitializer checks if the model for the Context is up to date from a table with all versions for all context classes stored in the database, and if it is not, it restores the EF dbo._MigrationHistory table for that Context class, then it does the normal EF Migrations. After the migration it stores the dbo._MigrationHistory per Context class to another table. It does not support automigrations.

    Hopes this helps some people.

    (BTW, the library is really cool, it also implements:

    - lazy loading of dll's for fast application startup.
    - A VirtualPathProvider for dll Resources.
      Simply set the property of an aspx file to "Resource" and you have the page in your website only from including a dll without an aspx file in your website.
    - Extensible through Service / Provider Model
    - Log & Debug support.
    - Html Processing.
    - Useful LINQ extensions.
    - Classes for easy handling of config files.
    - Support for multiple domains via url rewrite.
    - Easy classes for file handling.
    - FTP Folder synchronisation (still has bugs)
    - Generic DataSource control for CodeFirst.
    - Role & Membership Provider using CodeFirst.
    - Pluggable JavaScript Editor (with CKEditor as plugin).
    - File Manager (not yet finished)
    - Content controls that implement dynamically editable content that gets stored directly in the aspx page and can be equally edited in VS or from the website. (not yet finshed).
     - Dynamic generation of images, pdf, html image maps & animated gifs from XAML. (Not yet published, still has bugs)


    • Edited by David Egli Wednesday, December 19, 2012 11:25 AM
    Sunday, July 1, 2012 4:32 PM