在Entity Framework5/6迁移中,是否有任何迁移属性或单例类返回当前连接字符串?我需要这个内部的迁移“向上”的方法,我知道这可能听起来很奇怪,但我需要它来执行一些特定的自动化…
发布于 2013-04-25 06:09:48
Up方法未连接。它只生成稍后将由DbMigrator执行的操作。如果您想在迁移过程中对连接执行任何操作,那么您唯一的选择就是Seed方法。
发布于 2013-04-25 06:11:05
这听起来确实有点'unortodox‘:),但是...
我建议使用Configuration的Seed方法
var connection = context.Database.Connection.ConnectionString;对于向上/向下迁移,您可以这样做:
当你有一个“正在运行”的DbContext时,这是可行的。
using (var db = new YourDbContext())
{
var connection = db.Database.Connection.ConnectionString;
}(我没有尝试过-因为它应该运行)
编辑:如何在没有DbContext (实体框架)的情况下获取连接缓存:
我想我现在明白你想做什么了(基于评论)。
您可以使用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();你可以把它放到Up/Down中--你应该会得到一个被使用的“不同的”连接。
如果你不混用不同的连接,这是可行的。在这种情况下,您需要根据您的场景对其进行调整。
(应该同时适用于EF5和EF6,类是相同的-我只是在EF5中快速确认了一下):
享受:)
https://stackoverflow.com/questions/16202696
复制相似问题