Entity framework 6 with MariaDB using C#

Hi,

In this post I am keen to illustrate the usage of entity framework 6 with MariaDB.

In my years of experience using entity framework it has improved a lot and came a long way, and now I like it so much that usually all my app’s which have interaction with databases will most likely have sprinkle of entity framework in them.

So getting to the business,

Create a new console application, and add the following nuget packages:

https://www.nuget.org/packages/EntityFramework/

https://www.nuget.org/packages/MySql.Data.Entity/6.10.9

Once the above packages are added to the project, then I would go ahead to create the following class:

MySqlDemoDbContext.cs


namespace ConsoleApp1
{
    [DbConfigurationType(typeof(MySqlEFConfiguration))]
    class MySqlDemoDbContext : DbContext
    {
        public MySqlDemoDbContext() : base("name=MySqlDemoDb")
        {

        }
    }
}

and the corresponding config file in the project will have the following entry

app.config


  <connectionStrings>
    <add name="MySqlDemoDb" 
         connectionString="server=ServerName;port=3306;database=DemoDB;uid=UserName;password=****" 
         providerName="MySql.Data.MySqlClient" />
  </connectionStrings>

and voila done, now the application is ready configured to leverage entity framework feature’s with MariaDB backend.

Program.cs


class Program
    {
        static void Main(string[] args)
        {
            using (var db = new MySqlDemoDbContext())
            {
                var zz = db.Database.SqlQuery<string>("SELECT FirstName FROM Test;").ToList();
                db.Database.ExecuteSqlCommand("UPDATE Test SET FirstName = 'User' WHERE Id = 4;");
            }

        }
    }

The above configuration, refrence articles are listed below:

https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework60.html

Hope it helps.

Leave a Reply

Your email address will not be published. Required fields are marked *

*