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 完得还原。