ASP.NET API: No database provider has been configured for this DbContext
ASP.NET API: No database provider has been configured for this DbContext
I am trying to connect to a MySql database from my .Net Core API project.
This is my context class:
public class MyContext : DbContext
public MyContext()
public MyContext(DbContextOptions<MyContext> options)
: base(options)
public MyContext(DbContextOptions options)
: base(options)
...
and this is my startup.cs:
public void ConfigureServices(IServiceCollection services)
services.AddMvc();
string MyConnectionString = "server=localhost;port=3306;user=root;password=*****;database=my_db";
services.AddDbContext<MyContext>(options => options.UseMySQL(MyConnectionString));
I know this question has already been asked a million times, but I still can't fix it.
Edit: In controllers, I instantiate my MyContext
using the parameterless constructor.
MyContext
no port name required and write the instance name (sql server name) this should work, if that the case let me know so I can leave you an answer.
– maytham-ɯɐɥʇʎɐɯ
Sep 12 '18 at 12:46
Try to put 'services.AddMvc()' as the last operation of your method.
– greyxit
Sep 12 '18 at 12:48
Are you using .NET Core 2.1 ? Cause, if I undestand correctly, it is not supported : dev.mysql.com/doc/connector-net/en/…
– greyxit
Sep 12 '18 at 12:53
Try to remove the default constructor of your dbcontext (public MyContext() )
– greyxit
Sep 12 '18 at 12:58
1 Answer
1
Let's try something else :
First, in your DbContext create OnConfiguring
method :
OnConfiguring
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
optionsBuilder
.UseMYSQL("... connection string ...");
Secondly, on the beginning of you ConfigureServices
method, configure the DbContext this way :
ConfigureServices
services.AddDbContext<MyContext>();
That actually worked, thanks! Is there an explanation of why my code didn't work? Because I found it on Microsoft's website :-)
– Eutherpy
Sep 12 '18 at 13:10
No idea.. I suppose the "dbcontext black box" called your parameter-less constructor. My way forces the configuration every time, not only on application start... Could you please mark the answer as accepted ? :)
– greyxit
Sep 12 '18 at 13:14
Of course, thanks again!
– Eutherpy
Sep 12 '18 at 13:17
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
try with this Server=.\instanceName;Database=my_db;User Id=root;Password=********;
– maytham-ɯɐɥʇʎɐɯ
Sep 12 '18 at 12:46