希格工作室

2019年9月30日 星期一

.NET Core 2.1 DI AddDbContext BUG

.NET Core 2.1 bug

錯誤訊息:
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

原因:
透過AddDbContext進來的EFCore會發生optionsBuilder.IsConfigured永遠為true,造成無法運作,直到更新至2.1.11才被修正

過程:
Code-first加入方式Scaffold-DbContext

Startup.cs
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDbContext<Models.Test.TContext>();
        }


ValuesController.cs
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly Models.Test.TContext context;

        public ValuesController(Models.Test.TContext context)
        {
            this.context = context;
        }

        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            var tb = context.Table2.FirstOrDefault();
            return new string[] { "value1", "value2" };
        }
    }
}


Context.cs








修正方式:
三種修正方式(擇一即可)
1.更新至.Net Core 2.1.11up或.Net Core 2.2
2.如果將Context透過繼承也會避開
3.改使用AddTransient<T>註冊



2.將Context透過繼承也會避開















































3.改使用AddTransient<T>註冊












結語:
能更新上去就更新上去,但因為我平台在AWS上,而aws toolkit for visual studio的預設專案範本不支援.NET Core2.2up,若要使用過於複雜不適合目前環境,故只能持續使用2.1版,所以更新2.1.11版是最佳解,其次是透過繼承也能順便解決其它自定義的東西。





沒有留言:

張貼留言