Search code examples
c#asp.net-coreentity-framework-core

I am getting an error when I try to add migration in ASP.NET Core application which I connected with MySQL server of xamp


This is the error I get:

Unable to create a 'DbContext' of type ''. The exception 'Method not found: 'Void CoreTypeMappingParameters..ctor(System.Type, Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter, Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer, Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer, Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer, System.Func`3<Microsoft.EntityFrameworkCore.Metadata.IProperty,Microsoft.EntityFrameworkCore.Metadata.IEntityType,Microsoft.EntityFrameworkCore.ValueGeneration.ValueGenerator>)'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Connection

"dbcs": "Server=localhost;Port=3307;Database=asp1;user=root;password=;" //this is located in json file
var connectionString = builder.Configuration.GetConnectionString("dbcs");
builder.Services.AddDbContext<StudentDbContext>(item =>
{
    item.UseMySql(connectionString,ServerVersion.AutoDetect(connectionString));
});
var app = builder.Build();

DbContext:

using Microsoft.EntityFrameworkCore;

namespace WebApplication2.Models
{
    public class StudentDbContext:DbContext
    {
        public StudentDbContext(DbContextOptions op) : base(op)
        {    
        }

        public DbSet<StudentModel> Students { get; set; }
    }
}

Model class:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApplication2.Models
{
    public class StudentModel
    {
        [Key]
        public int Id { get; set; }
        [Required(ErrorMessage = "Fill the name")]
        [Column("Student Name", TypeName="varchar(20)")]
        public string Name { get; set; }   
        public int Age { get; set; }

        public string Gender { get; set; }
    }
}

How can I solve this error? This is for .NET 8 and EF Core 8


Solution

  • I reproduced the error with following package version
    enter image description here enter image description here

    Microsoft.EntityFrameworkCore(8.0.0)
    Microsoft.EntityFrameworkCore.Design(8.0.0)
    Microsoft.EntityFrameworkCore.Tools(8.0.0)
    Pomelo.EntityFrameworkCore.MySql(7.0.0)
    

    The issue disappeared with follwing package version:
    enter image description here enter image description here

    Microsoft.EntityFrameworkCore(7.0.14)
    Microsoft.EntityFrameworkCore.Design(7.0.14)
    Microsoft.EntityFrameworkCore.Tools(7.0.14)
    Pomelo.EntityFrameworkCore.MySql(7.0.0)
    

    Since Pomelo.EntityFrameworkCore.Mysql lasted support version is 7.0.0, it is better keep all the efcore related packages to version 7.X.