EFCore 入門遇到的幾個問題


1.  配置的GetConnectionString 怎么取不到鏈接數據庫的字串?

   public void ConfigureServices(IServiceCollection services)
   {
      services.AddDbContext<EntityContext>(options => options.UseSqlServer(_Configuration.GetConnectionString("DbConnection"))); }

json 文件:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionString": {
    "DbConnection": "Server=(localdb)\\mssqllocaldb;Database=EntityDb;Trusted_Connection=True;"
  }
}

 查詢官方文檔得知 json 配置的字串少一個s, 

 ConnectionString->ConnectionStrings

還遇到一次,加了s怎么還是取不到?仔細看配置文件,別把配置寫到Logging 節點里面去了。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "DbConnection": "Server=(localdb)\\mssqllocaldb;Database=ForestryDB;Trusted_Connection=True;"
  }
}

2. 在PMC 中執行Add-Migration 不能識別,可能你沒有安裝Microsoft.EntityFrameworkCore.Tools 包

PM> Add-Migration
Add-Migration : The term 'Add-Migration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Add-Migration
+ ~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Add-Migration:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 

總結下需要安裝的包,

Repository 需要安裝兩個包

 1.Microsoft.EntityFrameworkCore.SqlServer

 2.Microsoft.EntityFrameworkCore.Tools

項目啟動文件需要安裝

 1.Microsoft.EntityFrameworkCore.SqlServer

 2.Microsoft.EntityFrameworkCore.Design

配置中還可以指定生成的遷移文件在哪個程序集里面

  services.AddDbContext<EntityDBContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DbConnection"), builder=> { builder.MigrationsAssembly("DL.Forestry.Repository"); });
            });

 引入Serilog 后重寫了加載配置的方法,發現不能EF 不能migration,一直報錯執行不成功,趕快打開調試模式Verbose查看詳細錯誤  add-migration "modified user" -verbose

Using environment 'Development'.
System.ArgumentNullException: Value cannot be null. (Parameter 'config')
   at Microsoft.Extensions.Configuration.ChainedBuilderExtensions.AddConfiguration(IConfigurationBuilder configurationBuilder, IConfiguration config, Boolean shouldDisposeConfiguration)
   at Microsoft.Extensions.Configuration.ChainedBuilderExtensions.AddConfiguration(IConfigurationBuilder configurationBuilder, IConfiguration config)
   at DL.Forestry.WebApi.Program.<>c.<CreateHostBuilder>b__3_0(IConfigurationBuilder configurationBuilder) in D:\Forestry\DL.Forestry.WebApi\Program.cs:line 59
   at Microsoft.Extensions.Hosting.HostBuilder.BuildHostConfiguration()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Value cannot be null. (Parameter 'config')
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'EntityDBContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'EntityDBContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[DL.Forestry.Repository.EntityDBContext]' while attempting to activate 'DL.Forestry.Repository.EntityDBContext'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'EntityDBContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

錯誤在59 行,先以為是沒有執行到config 里面的appsetting.json. 於是手動addjson 還是無效,打斷點,斷點也沒進來,奇怪怎么回事?仔細看代碼 59 行我們重寫了系統的委托 ConfigureHostConfiguration

后來查資料得知,原來EFCore在執行遷移的時候不執行Main方法,直接調用 ConfigureHostConfiguration 這個默認委托的實現(core 3.1 里是這樣,后續版本不清楚是不是會更新),這里我們重寫了,所以加載不到系統配置,注釋掉寫的委托,OK了,記得migration 完得還原。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM