我发现 EF 启动缓慢的很大一部分可能与从数据库中获取提供程序信息有关。这在运行集成测试或进行其他迭代开发时非常烦人。谁能解释为什么获取提供者信息很慢或者可以做些什么?我们正在使用 EF5。
这是一个演示此行为的示例:
void Main()
{
Database.SetInitializer<ModelDbContext>(null);
Database.SetInitializer<ModelCreatingDbContext>(null);
// passing the provider information in is very fast
var sw2 = Stopwatch.StartNew();
var builder = new DbModelBuilder();
builder.Entity<SqlConnectionStringBuilder>().HasKey(c => c.ConnectionString).ToTable("strings");
var q2 = new ModelDbContext(builder.Build(new DbProviderInfo("System.Data.SqlClient", "2008")).Compile()).Set<SqlConnectionStringBuilder>().Take(1).ToString();
Console.WriteLine(sw2.Elapsed); // < 1 second
// letting EF determine it from the connection string is sometimes very slow
var sw1 = Stopwatch.StartNew();
var q = new ModelCreatingDbContext().Set<SqlConnectionStringBuilder>().Take(1).ToString();
Console.WriteLine(sw1.Elapsed); // can be upwards of 13 seconds!
}
public class ModelDbContext : DbContext {
public static readonly string Connection = // connection string here
public ModelDbContext(DbCompiledModel model)
: base(Connection, model) { }
}
public class ModelCreatingDbContext : DbContext {
public ModelCreatingDbContext() : base(ModelDbContext.Connection) { }
protected override void OnModelCreating(DbModelBuilder builder) {
builder.Entity<SqlConnectionStringBuilder>().HasKey(c => c.ConnectionString).ToTable("strings");
base.OnModelCreating(builder);
}
}