2017-02-08 16 views
0

我有我的dotnet核心項目與實體框架核心和mysql連接器的性能問題。在我的控制器http://insidemysql.com/howto-starting-with-mysql-ef-core-provider-and-connectornet-7-0-4/增加實體框架連接和查詢

public class MhdContext : DbContext 
    { 
     public MhdContext(DbContextOptions<MhdContext> options) : base(options) { } 

     public DbSet<Vehicle> Vehicles { get; set; } 
    } 

    public static class MhdContextFactory 
    { 
     public static MhdContext Create(string connectionString) 
     { 
      var optionsBuilder = new DbContextOptionsBuilder<MhdContext>(); 
      optionsBuilder.UseMySQL(connectionString); 

      //Ensure database creation 
      var context = new MhdContext(optionsBuilder.Options); 
      context.Database.EnsureCreated(); 
      var serviceProvider = context.GetInfrastructure<IServiceProvider>(); 
      var loggerFactory = serviceProvider.GetService<ILoggerFactory>(); 
      loggerFactory.AddProvider(new MyLoggerProvider()); 

      return context; 
     } 
    } 

我調用這個方法:

我創建的DbContext通過下面的教程

public async Task<Vehicle[]> GetAllVehicles() 
    { 
     _logger.LogInformation("Getting All vehicles"); 
     using (var dbContext = MhdContextFactory.Create(_dbConfig.ConnectionString)) 
     { 
      var vehicles = await dbContext.Vehicles.AsNoTracking() 
       .FromSql("SELECT * FROM Vehicles AS v group by v.VehicleId order by LastUpdate") 
       .ToArrayAsync(); 
      return vehicles; 
     } 
    } 

第一要求一切看起來像工作

有幾個請求後後是重複的sql命令並且正在增加 第7次請求日誌:https://www.dropbox.com/s/2ezyowyubq1orsn/7thRequest.txt?dl=0

你能幫我解決我做錯了什麼嗎?

回答

0

我不會創建一個靜態工廠來返回上下文。實體框架(EF)中的「上下文」是對數據庫的開放。您可能遇到麻煩,您正在重複使用相同的連接進行不同的查詢。一般來說,靜態對於諸如公共靜態添加(int x,int y){Return x + y}等核心業務用法來說是非常好的。但對於像數據訪問這樣的事情,我會避免它們並支持基於實例。也許我錯了,還有一些高級EF專家會進來解釋一下。在該專業採用EF公司

(var context = new EFContext()) // NOT BASED ON FROM A STATIC FACTORY 
{ 
    //Do some DB operation 
} 

在我的工作經歷:但通常我總是被包裝在一個事務因此這裏的一切都包含在那裏處理我的上下文中。如果他們試圖使用IOC來共享EF的靜態或實例,則會隨着時間的推移而被分散。當你堅持打開,建立連接,做某件事情,關閉它與處理IT(這是通過使用'使用{}'塊自動處理)它表現更好。

0

我終於解決了這個與添加到我的startup.cs這樣的:

public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddDbContext<MhdContext>(
      options => options.UseMySQL(
       Configuration.GetConnectionString("MysqlConnection"))); 
    } 

所以我的分貝contexte看起來像現在這個樣子:

public MhdContext(DbContextOptions<MhdContext> options) : base(options {} 

在我的控制,我得到實例與depencency注射:

var dbContext = _serviceProvider.GetService<MhdContext>(); 
    return dbContext.Vehicles;