I try to connect my MySQL database to the test code of the ASP.NET Core (v2.1) application. I created a sample application and added the MySql.Data.EntityFrameworkCore
nuget package...
Bellow is my code:
// Context
public class EntriesContext: DbContext
{
public EntriesContext(DbContextOptions<EntriesContext> options) : base(options) { }
public DbSet<Entry> Entries { get; set; }
}
// Controller
[ApiController, Route("api/[controller]")]
public class EntriesController : ControllerBase
{
private readonly EntriesContext _context;
public EntriesController(EntriesContext context) {
_context = context;
_context.Database.EnsureCreated();
if (_context.Entries.Count() == 0) {
_context.Entries.Add(new Entry {
From = "default@from.com", To = "default@to.com",
Message = "default message", Site = "default site"
});
_context.SaveChanges();
}
}
[HttpGet]
public ActionResult<List<Entry>> GetAll() {
return _context.Entries.ToList();
}
// Startup
public void ConfigureServices(IServiceCollection services) {
services.AddDbContext<EntriesContext>(
opt => opt.UseMySQL("server=localhost;database=mydb;user=myuser;password=mypass"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
the Model is like this:
public class Entry
{
public Entry() {
this.Date = DateTime.UtcNow
.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
.TotalMilliseconds;
}
public Entry(long id, string site, string from, string to, string message) : this() {
this.Id = id;
this.Site = site;
this.From = from;
this.To = to;
this.Message = message;
}
When I launch the application, I get the following:
System.MissingMethodException
HResult=0x80131513
Message=Method not found: 'Void Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory..ctor(Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger`1<Command>, Microsoft.EntityFrameworkCore.Storage.IRelationalTypeMapper)'.
Source=MySql.Data.EntityFrameworkCore
StackTrace:
at MySql.Data.EntityFrameworkCore.Storage.Internal.MySQLCommandBuilderFactory..ctor(IDiagnosticsLogger`1 logger, IRelationalTypeMapper typeMapper)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at [...]
at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.get_DatabaseCreator()
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()
at LoggerApi.Controllers.EntriesController..ctor(EntriesContext context) in C:\MyProjects\WebApplication1\WebApplication1\Controllers\EntriesController.cs:line 19
at [...]
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__13.MoveNext()
could someone suggest where is the problem here?
Try add package https://www.nuget.org/packages/Pomelo.EntityFrameworkCore.MySql/
Version 2.1.2
I worked for me
User contributions licensed under CC BY-SA 3.0