2 Comments

If you want to set the connectionstring for a dbcontext, when using EntityFramework 4.2, just create a partial class for the specific dbcontext and add a constructor that call’s de dbcontext constructor with connectionstring. Now you can instantiate MyDatabaseEntities with a connectionstring.

 

public partial class MyDatabaseEntities
    {
        public MyDatabaseEntities(string connection)
            : base(connection)
        {
        }
    }

The generated partial class looks something like:

 

public partial class MyDatabaseEntities : DbContext
    {
        public MyDatabaseEntities()
            : base("name=MyDatabaseEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public DbSet<Products> Products { get; set; }

    }

2 Replies to “How to set the connectionstring at runtime of a dbcontext in Entity Framework 4.2”

  1. Hi
    It throws exception UnintentionalCodeFirstException:

    Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.

  2. Sample dont work
    It throws exception UnintentionalCodeFirstException

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts