簡體   English   中英

如何在實體框架遷移中獲取當前連接字符串?

[英]How to get the current connection string inside an Entity Framework migration?

是否有任何遷移屬性或單例類返回實體框架 5/6 遷移中的當前連接字符串? 我需要在遷移“Up”方法中使用它,我知道這聽起來很奇怪,但我需要它來執行一些特定的自動化......

Up方法未連接。 它只生成稍后將由DbMigrator執行的DbMigrator 如果您想在遷移期間對連接進行任何操作,您唯一的機會就是使用Seed方法。

嗯,這聽起來確實有點“非正統”:),但是......

我建議使用您的ConfigurationSeed方法

var connection = context.Database.Connection.ConnectionString;

對於向上/向下遷移,您可以執行以下操作...

當您有一個“正在運行”的 DbContext 時,這會起作用。

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

(我沒有嘗試 - 因為它應該運行)


編輯:如何在沒有 DbContext(實體框架)的情況下獲取連接緩存:


我想我現在明白你想要做什么(基於評論)。

您可以使用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 快速確認了它):

享受 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM