从数据库获取提供程序信息时,EF非常慢

时间:2013-11-02 16:53:00

标签: c# sql-server linq entity-framework

我发现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);
    }
}

0 个答案:

没有答案