Mike Borozdin's Blog

A blog about programming, web and IT in general

LINQ To MySQL

LINQ to SQL is a great tool that saves a lot of time. However it has one disadvantage – it supports only SQL Server. Anyway it’s possible to write your own LINQ provider. Sure, there is one for MySQL. It is called DbLinq, in fact in supports many databases:

  • MySQL
  • Oracle
  • PostreSql
  • Ingress
  • SqlLite
It’s not finished yet, however you can still try to use it. I’m going to explain how to use it in this article; we’ll go through 3 steps:
  1. Installation
  2. Using DbLinq in a console application
  3. Using DbLinq in a ASP.NET application

Installation

  1. Go here and download the ZIP archieve
  2. Unpack the archive
  3. Open the Visual Studio solution - DbLinq
  4. Build the solution

Using DbLinq in a console application

Ok, let’s try it in action, we are going to create a console application that will retrieve, insert, update and delete records from the database.

First, we need to generate the data context and the table classes. Unfortunately you cannot do this in Visual Studio, but there is a command line utility called DbMetal and its visual analogue – Visual Metal that is written in WPF, by the way.


Go to the \dblinq2007\DbMetal\ folder, there are several BAT files, open in your favourite text editor run_myMetal.bat, since we are dealing with MySQL, and change the necessary parameters, save and run it. You must have got a generated CS file, copy it to your console application project.
Then, it’s time to add the references, you should add the following:

  • System.Data.Linq
  • DbLinq.dll (located in \dblinq2007\DbLinq.MySql\bin\release\)
  • DbLinq.MySql.dll (located in \dblinq2007\DbLinq.MySql\bin\release\)
  • MySql.Data.dll (located in \dblinq2007\lib\)

Since the table is called Products, I want the class that represents a stored entity to be called Product, not Products, as it was called by DbMetal. So, I change the generated code.


Compile the project to check if there are no errors. If you get any error, check if there are all the necessary references.


Let’s write some code; basically we want just to display the data:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient; //Don't forget to add this line

namespace MySqlLinqTest
{
    class Program
    {
        static void Main(string[] args)
        {
            LinqTest db = new LinqTest(new MySqlConnection("Database=<your database>;Data Source=localhost;User Id=<user>;Password=<password>"));

            var products = from p in db.Products
                           where p.Category == "Sport cars"
                           select p;

            foreach (var product in products)
            {
                Console.WriteLine(product.Name);
            }
        }
    }
}

That works. What about inserting a new record? No problems!

db.Products.InsertOnSubmit(new Product { Name = "Some car", Category = "Some category" });
db.SubmitChanges();

var products = from p in db.Products
               orderby p.Name
               select p; 

foreach (var product in products)
{
    Console.WriteLine(product.Name);
}

Ok, let’s remove the newly added record:

Product someCar = (from p in db.Products
                      where p.Name == "Some car"
                      select p).First();

db.Products.DeleteOnSubmit(someCar);
db.SubmitChanges();

Let’s update something:

Product bentley = (from p in db.Products
                   where p.Name == "Bentley"
                   select p).First();

bentley.Name = "Bentley Continental";
db.SubmitChanges();

Using DbLinq in an ASP.NET application

It was funny enough, but the console applications are not very useful when dealing with the database, let’s write something that is closer to a real world – an ASP.NET application.


Create a C# web site; copy the generated file we used in the previous example.


Don’t forget to add the necessary references.


We are going to add a GridView and bind the data retrieved from the database.

Default.aspx

<asp:GridView ID="gridProducts" runat="server">
</asp:GridView>

 

Default.aspx.cs 

protected void Page_Load(object sender, EventArgs e)
{
    LinqTest db = new LinqTest(new MySqlConnection("Database=<your database>;Data Source=localhost;User Id=<user>;Password=<password>"));

    gridProducts.DataSource = from p in db.Products
                              orderby p.Name
                              select p;
    gridProducts.DataBind();
}

It works.

What about LinqDataSource, can we use it with DbLinq? Yes, we can, but it’s a bit tricky. If we add a LinqDataSource, we’ll get an error saying that there’s no parametless constructor in our DataContext. That is a thing that hopefully will be fixed in the new versions, but now we have to write a wrapper around a generated DataContext.

App_Code/Products.cs

public class MyDataContext
{
    private LinqTest _db;

    public MyDataContext()
    {
        _db = new LinqTest(new MySqlConnection("Database=<your database>;Data Source=localhost;User Id=<user>;Password=<password>"));
    }

    public Table<Product> Products { get { return _db.GetTable<Product>(); } }
}

Then, we can use LinqDataSource as usual:


<asp:LinqDataSource ID="dsProducts" runat="server" ContextTypeName="MysqlLinqTest.MyDataContext"
    TableName="Products">
</asp:LinqDataSource>

<asp:GridView ID="gridProducts" runat="server" DataSourceID="dsProducts"> 
</asp:GridView>

Conclusion

As you see you can use LINQ to work with MySQL, unfortunately sometimes it’s not very convenient and we have to wait for the new versions or wait for a LINQ to MySQL provider from MySQL.
 


Tags:
Posted by Mike Borozdin on Thursday, June 26, 2008 8:30 AM GMT
  Shout it Kick it!  
Permalink | Comments (9) | Post RSSRSS comment feed

Comments

Mike Griffin United States

Thursday, June 26, 2008 9:26 AM GMT

Mike Griffin

Well, if this search www.mysql.com/.../ is any indication MySQL isn't too interested in LINQ support (with zero hits found). Good article on DbLinq I have been keeping my eyes on it. I wish the site gave more indication one what levels each database is supported.

Mike Borozdin Russia

Friday, June 27, 2008 1:55 PM GMT

Mike Borozdin

Well, this just means they don't support it at the moment and probably just don't disclose their plans on supporting it. I think if they have .NET Connector, they will make a LINQ to MySQL provider as well.

Jason United States

Wednesday, July 30, 2008 1:39 AM GMT

Jason

Thanks for the article.  Your article is one of only a handful of articles on the subject of LINQ to MySQL in recent times.

My understanding is that the current provider is not quite production-ready.  It's a pity as MySQL is available on most budget ASP.NET shared hosting plans; oh well, for now, we just have to access MySQL the conventional way.

Mike Borozdin Russia

Wednesday, July 30, 2008 8:37 AM GMT

Mike Borozdin

Hello Jason,

Thank you for taking time to read my article.

Well, the version I wrote about lack some features and probably not very stable. It's a bit dissapointing that MySQL haven't announced any plans regarding LINQ yet.

umesh India

Saturday, November 29, 2008 4:52 AM GMT

umesh

I have included DbLinq.dll, DbLinq.MySql.dll, System.Data.Linq and MySql.Data.dll in my application. Changed the run_myMetal.bat file as
REM: note that the '-sprocs' option is turned on

bin\DbMetal.exe -provider=MySql -database:employees -server:localhost -user:root -password:tiger -namespace:MySqlLinqTest -codeLaughingefault.aspx.cs -sprocs
to suit my database ie employees and the code is in Default.aspx.cs.

But while including the code given at the site the intelligence is not showing LinqTest also
the instance db is not showing the tables in my database.

Please guide us

Zeeshan

Wednesday, December 31, 2008 5:47 AM GMT

Zeeshan

Well thanx for this article. This article give me help to work LINQ with mySQL and as well as with PostGreeSQL databases. But i've a little problem regarding it. I need to ask one question that, this tool generates .CS file for mapping layer. I am trying to generate .dbml file with VisualMetal tool. It generates db maping layer but that layer not works.

One more thing i need to ask that, if i do changes in my databases mean add/delete any column from table, then should i again generate .Nortwind.cs file for maping???

Brett Australia

Wednesday, June 03, 2009 8:58 PM GMT

Brett

I am using DBLinq to connect to a MySQL DB on one of my ASP.NET apps but am running into trouble on the shared hosting as it runs in medium trust...

I have recompiled the DLL's with [assembly: AllowPartiallyTrustedCallers()] in the AssemblyInfo files for DBLinq.dll and DBLinq.MySQL.dll... This gets me past the SecurityException, but the following exception is now thrown:

Type 'DbLinq.Data.Linq.Sugar.IDataMapper' has no implementation

ArgumentException: Type 'DbLinq.Data.Linq.Sugar.IDataMapper' has no
implementation]
   DbLinq.Factory.Implementation.ReflectionObjectFactory.Create(Type
t) +202
   DbLinq.Factory.Implementation.ReflectionObjectFactory.Get(Type t)
+115
   DbLinq.Factory.ObjectFactoryExtensions.Get(IObjectFactory self)
+115
   DbLinq.Factory.ObjectFactory.Get() +124
   DbLinq.Data.Linq.DataContext..ctor(IDatabaseContext
databaseContext, MappingSource mappingSource, IVendor vendor) +145
   DbLinq.Data.Linq.DataContext..ctor(IDatabaseContext
databaseContext, IVendor vendor) +54
   DbLinq.Data.Linq.DataContext..ctor(IDbConnection dbConnection,
IVendor vendor) +76
   WhalesMVC.Models.Whales..ctor(IDbConnection connection) +73
   WhalesMVC.Helpers.DBHelper.GetDBConnection() +138


Any ideas???

sai India

Thursday, August 20, 2009 3:53 AM GMT

sai

hi , nice article but i tried with asp.net  web application here whenever i m binding the values to a grid it s giving err like "object reference not set to an object instance "

Any ideas r suggestions

Mike Borozdin Russia

Thursday, August 20, 2009 4:02 AM GMT

Mike Borozdin

@sai,

Run it in the debug mode and see which object is set to null.

Comments are closed