Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Using Entity Framework Core with MySQL 8.0 in WinForms Applications

Tech May 13 59

NuGet Package Requirements

This tutorial targets MySQL 8.0. The required NuGet packages are:

MySql.EntityFrameworkCore
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Relational

These packages are designed for .NET Core/.NET 5+ Windows Forms applications. Standard .NET Framework projects do not support these version 8.0 packages, and older package versions may have compatibility issues with MySQL 8.0. As long as the application runs succesfully, the setup is considered correct.

Creating the Database Context

Create a MyDbContext class that inherits from DbContext. This class handles the database connection and serves as the entry point for Entity Framework operations.

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WinFormsApp1.MySql
{
    public class MyDbContext : DbContext
    {
        public DbSet<data1> tb_data1 { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string connectionString = @"Server=localhost; Port=3306; Database=testdb; User=root; Password=yourpassword;";
            optionsBuilder.UseMySQL(connectionString);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // Exclude specific fields from database mapping without removing from the model
            // modelBuilder.Entity<EntityName>().Ignore(x => x.PropertyName);
            //
            // Example: Exclude the text1 field from the data1 table
            // modelBuilder.Entity<data1>().Ignore(x => x.text1);

            // For tables without primary keys, use the following approach
            // modelBuilder.Entity<EntityName>().HasNoKey();
        }
    }
}

Key Configuration Methods

OnConfiguring

This method recieves the connection string and configures the database provider. The UseMySQL() method establishes the connection to the MySQL server using the specified parameters including host, port, database name, and credentials.

OnModelCreating

This method handles entity configuration at the model level. Common operations include:

  • Ignoring properties: Use Ignore() to exclude specific model properties from database mapping
  • Configuring keys: Use HasKey() to specify primary key properties
  • Handling keyless entities: Use HasNoKey() for tables without defined primary keys

Usage Example

With the context configured, you can perform database operations within your WinForms application:

public partial class Form1 : Form
{
    private readonly MyDbContext _context;

    public Form1()
    {
        InitializeComponent();
        _context = new MyDbContext();
    }

    private void LoadData_Click(object sender, EventArgs e)
    {
        var records = _context.tb_data1.ToList();
        dataGridView1.DataSource = records;
    }
}

Always dispose of the context properly, preferably using a using statement or implementing IDisposable pattern to ensure database connections are closed appropriately.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.