Entity Framework With Mysql

packages you have to install

         <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="7.0.5" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Analyzers" Version="7.0.5" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.5">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
        <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="7.0.0" />

Create Tables Classes

assume we have two tables like this

Students table
Courses table

then we will build class or record for it like

PrimaryKey("StudentId")]
public class Student
{
    public string StudentId { get; set; }
    public string? StudentName { get; set; }
    public string? cid { get; set; }
    public Course? Course { get; set; }
}

[PrimaryKey("CourseId")]
public class Course
{
    
    public string CourseId { get; set; }
    [Required]
    public string? CourseName { get; set; }
    //public ICollection<Student> Students { get; set; }
}


build the context

public class SchoolContext : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
              // configure connection
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseMySql($"server=127.0.0.1;user=school;password=*******;database=FoodMenu",
                MySqlServerVersion.AutoDetect("server=127.0.0.1;user=schhol;password=*******;database=FoodMenu"));
        }
    }
    
    // build relations 
    protected sealed override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<Student>().HasOne<Course>(s => s.Course).WithMany().HasForeignKey("cid");
        //modelBuilder.Entity<Course>().HasMany<Student>(s => s.Students).WithOne(s=>s.Course).HasForeignKey((e)=>e.CourseId);
    }
}

then you can use it directly

using(SchoolContext context = new SchoolContext())
{
    var res2= context.Students.Include(s=>s.Course).ToList();
    foreach (var item in res2)
    {
        Console.WriteLine(JsonSerializer.Serialize(item).ToString());
    }
}

or use it as a service


builder.Services.AddDbContext<SchoolContext>(c =>
{
    c.UseMySql("connection string",  MySqlServerVersion.AutoDetect("connection string"));
});