Click here to Skip to main content
Click here to Skip to main content

Using MySQL with Entity Framework

, 23 Jul 2012
Rate this:
Please Sign up or sign in to vote.
Explains how to use MySQL with the Entity Framework.

Introduction

Entity Framework is the next level of database programming and is much more flexible and adoptable than earlier methods like ADO.NET and LINQ to SQL.

Prerequisites

  • Install Visual Studio 2008 or Visual Studio 2010
  • Install MySQL database on your local machine
  • MySQL database admin tool that allows you to create a database and run SQL statements. I am using phpMyAdmin which is a web interface.
  • Download and install MySQL Connector.

Getting Started

Run the XAMPP application and it will automatically install Apache server, MySQL database, and FileZilla. After installing check whether these services are running or not. The following XAMPP control panel shows which of those services are currently running.

The following steps will show how to connect to a MySQL database using C#.

Step 1

Open MySQL Admin page and create a new database.

Step 2

After creating the new database, create a new table.

CREATE TABLE `employee` (
  `EmpId` bigint (20) NOT NULL,
  `EmpName` varchar (200) default NULL,
  `EmpAddress` varchar (255) default NULL,
  PRIMARY KEY (`EmpId `)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 3

After creating the new table, open Visual Studio and click on New Project and name the project. It will open the new project, then click on Solution Explorer (F4), right click on “Reference” to add a new reference into the project. Reference those two .dll files to the project (MySql.dll (Win apps), MySql.Data.Entity.dll).

Step 4

In Solution Explorer, go to “System.Data” properties set “Copy Local” property is true.

The Copy Local property (corresponding to CopyLocal) determines whether a reference is copied to the local bin path. At run time, a reference must exist in either the Global Assembly Cache (GAC) or the output path of the project. If this property is set to true, the reference is copied to the output path of the project at run time.

Step 5

Add new Entity Data Model into the project.

Step 6

Select “Generate from database” in Entity Data Model Wizard.

Step 7

Select MySQL database.

Step 8

Set Connection properties for MySQL.

Step 9

This step will display all the tables, views, stored procedure.

Step 10

By double clicking on Model1.edmx, it will open EDM designer which displays all the entities for selected tables.

Step 11

The following code will insert the data into MySQL table.

private void btnInsert_Click(object sender, EventArgs e)
{
    testdbEntities testcontext = new testdbEntities();
    try
    {

        employee emp = new employee

                   {
                       EmpId = int.Parse(txtId.Text),
                       EmpName = txtName.Text,
                       EmpAddress = txtAddress.Text
                   };
        testcontext.employee.AddObject(emp);
        testcontext.SaveChanges();
        MessageBox.Show("Record Inserted successfully.");
        LoadToGrid();
    }
    catch (Exception ex)
    {

        MessageBox.Show(ex.InnerException.ToString());
    }
}

Step 12

The following code will update the data into MySQL table.

private void btnUpdate_Click(object sender, EventArgs e)
{
    int EmpId;
    string s = txtId.Text;
    int.TryParse(s, out EmpId);
    testdbEntities testcontext = new testdbEntities();
    try
    {
        employee emp = testcontext.employee.First(i => i.EmpId == EmpId);
        {
            emp.EmpName = txtName.Text;
            emp.EmpAddress = txtAddress.Text;
            testcontext.SaveChanges();
            MessageBox.Show("Record Updated successfully.");
            LoadToGrid();
        };
    }
    catch (Exception ex)
    {

        MessageBox.Show(ex.InnerException.ToString());
    }
}

Step 13

The following code will delete the data into MySQL table.

private void btnDelete_Click(object sender, EventArgs e)
{
    int EmpId;
    string s = txtId.Text;
    int.TryParse(s, out EmpId);
    testdbEntities testcontext = new testdbEntities();
    try
    {
        employee emp = testcontext.employee.First(i => i.EmpId == EmpId);
        testcontext.employee.DeleteObject(emp);
        testcontext.SaveChanges();
         MessageBox.Show("Record Deleted successfully.");
        LoadToGrid();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.InnerException.ToString());
    }
}

Step 14

The following function will load the data from the table and bind it into a GridView.

private void LoadToGrid()
{
    testdbEntities testcontext = new testdbEntities();
    var load = from g in testcontext.employee select g;
    if (load != null)
    {
        dataGridView1.DataSource = load.ToList();
    }
}

Step 15

Final result:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ravindra T C
Software Developer L&T IES Mysore
India India
I'm a software developer. I spent most of the time in learning new technologies. I've a keen interest in client-side technologies especially JavaScript and Jquery it is the most beautiful language ever seen.

I like sharing my knowledge and written some non-popular articles. I believe in quality and standards but blames myself for lagging them.

I believe in small things and they makes me happy!

Comments and Discussions

 
Questionwamp PinmemberDhamx31-Aug-14 5:36 
SuggestionStep 12 Code PinprofessionalDamithSL29-Apr-14 16:22 
QuestionMySql.dll [modified] PinmemberHugo E.28-Apr-14 5:19 
QuestionHow to run program in other PC? Pinmemberaolin.wang17-Feb-14 16:27 
GeneralThank you Pinmemberashenupendra20-Jan-14 18:06 
QuestionStoked on Step 7 Pinmembergetskay20-Sep-13 4:01 
AnswerRe: Stoked on Step 7 Pinmembermaev2-Oct-13 16:58 
GeneralMy vote of 5 PinmemberHumberto Quijano8-Aug-13 7:00 
QuestionVery nice Artical... PinmemberShailendraP5-Jul-13 23:56 
AnswerRe: Very nice Artical... PinmemberRavindra T C6-Jul-13 6:35 
QuestionGood one PinmemberDorababu7437-Dec-12 21:53 
QuestionMore about this ... PinmemberDado_sylca17-Nov-12 0:29 
GeneralMy vote of 5 PinmemberPepLamb12-Nov-12 12:56 
GeneralMy vote of 5 PinmemberRene Pilon30-Oct-12 6:05 
GeneralMy vote of 5 PinmemberKbrKnight24-Jul-12 23:53 
GeneralRe: My vote of 5 PinmemberRavindra T C25-Jul-12 0:15 
QuestionGood Article PinmemberKbrKnight24-Jul-12 23:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140902.1 | Last Updated 23 Jul 2012
Article Copyright 2012 by Ravindra T C
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid