Print Page | Close Window

Code First Migration using DataSourceKey

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=3800
Printed Date: 13-May-2026 at 1:02am


Topic: Code First Migration using DataSourceKey
Posted By: Vonzkie
Subject: Code First Migration using DataSourceKey
Date Posted: 15-Nov-2012 at 2:43am
Hi,

We are trying to use Code First Migration in our database and it works well but the limitation is the connection string should be in the Web.config.

How can we do this process by invoking the IDataSourceKeyResolver or any way to dynamically compose the connection string to update the database.

Note that I'm doing the Update-Database command via code not in the Package Manager Console.

var migratorConfig = new Model.Migrations.Configuration();
var dbMigrator = new DbMigrator(migratorConfig);
dbMigrator.Configuration.AutomaticMigrationDataLossAllowed = false;
dbMigrator.Update();

Thanks,
Von



Replies:
Posted By: sbelini
Date Posted: 15-Nov-2012 at 10:58am
Hi Von,
 
Since Migration does not rely on DevForce, (i.e. it's pure EF) IDataSourceKeyResolver does not play a role in it and you will have to use the connectionString in the .config file.
 
   sbelini.


Posted By: Vonzkie
Date Posted: 15-Nov-2012 at 2:57pm
Hi Silvio,

Thanks for the info.
However, do you have an idea if EF has a dynamic way on constructing the connection string on Migration?

I ask this because our BOS' model handles not only one connection to the database and we use IDatasourceKeyResolver to compose the connection string.

Model1 can connection to Database A, Database B, Database C. So how do I perform automatic migration here in the production environment?

Thanks,
Von


Posted By: sky40627
Date Posted: 26-Nov-2012 at 10:38pm
Any answers to this question, I am trying to do the same.

Without any luck so far.

I also have a BOS that can connect to different databases.

Thx

Koen


Posted By: Vonzkie
Date Posted: 26-Nov-2012 at 10:50pm
Hi Koen,

We have created a workaround that might help you as well.

On your Custom DbContext:

    public class GlobalDBContext : DbContext
    {
        public GlobalDBContext() :
             base(Web.GetLatestMigrationConnection("MyEntities") ?? "name=MyEntities")
        {

        }
    }

Just add a method call on the base Constructor parameter that compose your connection string on runtime.

Note that when you're creating migration script via Package Manager Console (Add-Migration 'Something') you need to comment out this base(Web.GetLatestMigrationConnection("MyEntities") ?? "name=MyEntities")
and replace it with a basic base("name=MyEntities") that gets connection string from your app.config.
The code that I gave you above only works on production runtime. :)

Thanks,
Von





Print Page | Close Window