如何在实体框架迁移中获取当前连接字符串

本文关键字:获取 连接 字符串 迁移 实体 框架 | 更新日期: 2023-09-27 18:10:50

是否有任何迁移属性或单例类在实体框架5/6迁移中返回当前连接字符串?我需要这个在迁移"Up"方法中,我知道这听起来可能很奇怪,但我需要这个来执行一些特定的自动化…

如何在实体框架迁移中获取当前连接字符串

未连接Up方法。它只生成稍后由DbMigrator执行的操作。如果您想在迁移期间使用连接做任何事情,您唯一的机会是Seed方法。

这听起来确实有点"不正统":),但是…

我建议使用你们的ConfigurationSeed方法

var connection = context.Database.Connection.ConnectionString;

对于向上/向下迁移,你可以这样做…

当你有一个'running' DbContext时,这个工作。

using (var db = new YourDbContext())
{
    var connection = db.Database.Connection.ConnectionString;
}

(我没有尝试-因为它应该运行)


编辑:如何获取连接缓存w/o DbContext (Entity Framework):


我想我现在明白你想做什么了(基于评论)。

你可以通过Reflectioninternal 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();

您可以将其放入Up/Down -并且您应该得到一个使用的"不同"连接。

如果您不混合不同的连接,则此操作有效。在这种情况下,您需要根据您的场景对其进行调整。

(应该适用于EF5和EF6,类是相同的-我刚刚确认了EF5):

享受:)