[英]How to get the current connection string inside an Entity Framework migration?
Is there any migration property or singleton class the returns the current connection string inside a Entity Framework 5/6 migration?是否有任何迁移属性或单例类返回实体框架 5/6 迁移中的当前连接字符串? I need this inside of the migration "Up" method, I know it may sounds strange but I need this to perform some specific automation...
我需要在迁移“Up”方法中使用它,我知道这听起来很奇怪,但我需要它来执行一些特定的自动化......
The Up
method is not connected. Up
方法未连接。 it only generates operations that will be executed later by the DbMigrator
.它只生成稍后将由
DbMigrator
执行的DbMigrator
。 If you want to do anything with a connection during a migration your only chance is the Seed
method.如果您想在迁移期间对连接进行任何操作,您唯一的机会就是使用
Seed
方法。
Well it does sound a bit 'unortodox' :), but...嗯,这听起来确实有点“非正统”:),但是......
I'd suggest to use the Seed
method of your Configuration
我建议使用您的
Configuration
的Seed
方法
var connection = context.Database.Connection.ConnectionString;
For migration Up/Down you could do something like this...对于向上/向下迁移,您可以执行以下操作...
This works when you have a 'running' DbContext.当您有一个“正在运行”的 DbContext 时,这会起作用。
using (var db = new YourDbContext())
{
var connection = db.Database.Connection.ConnectionString;
}
(I didn't try that - as it should run) (我没有尝试 - 因为它应该运行)
You can get all connections
using Reflection
and from an internal static dictionary
您可以使用
Reflection
和internal static dictionary
获取all connections
IEnumerable<string> EnumerateConnections() { var lazyInternalContextType = typeof(DbContext).Assembly .GetType("System.Data.Entity.Internal.LazyInternalContext"); var propertyDbs = lazyInternalContextType.GetField( "InitializedDatabases", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); var lazyContext = propertyDbs.GetValue(null); foreach (var pair in (IEnumerable)lazyContext) { var key = pair.GetType().GetProperty("Key")?.GetValue(pair, null); var tuple = (Tuple<System.Data.Entity.Infrastructure.DbCompiledModel, string>)key; yield return tuple.Item2; // need to replace "System.Data.SqlClient.SqlConnection;" with "" in EF6. } } var connectionName = EnumerateConnections().Distinct().SingleOrDefault();
You can put that into Up/Down - and you should get one 'distinct' connection that was used.您可以将其放入 Up/Down - 并且您应该获得一个已使用的“不同”连接。
This works providing you do not mix different connections.如果您不混合不同的连接,则此方法有效。 In that case you'd need to tweak this based on your scenario.
在这种情况下,您需要根据您的情况进行调整。
(should work for both EF5 and EF6, classes are the same - I just confirmed it fast for EF5): (应该适用于 EF5 和 EF6,类是相同的 - 我刚刚为 EF5 快速确认了它):
Enjoy :)享受 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.