Connecting to MySQL Database with ASP.NET Web Pages (Razor)

John Avis by | May 20, 2011 | ASP.NET Web Pages Web Development

This is how you can connect to a MySQL database from ASP.NET Web Pages (Razor).
To connect to a MySQL database from ASP.NET Web Pages (Razor) you need to do the following:

1. Add a "Bin" ASP.NET folder to your project and copy the file MySQl.Data.dll in to it.

You can obtain this file by downloading the latest version of the MySQL Connector/NET (, installing it, then locate the file in the installation folder.

2. In your web.config file add a connection string for your database, for example:

<add name="Any-name" connectionString="Server=server-name-or-ip;Port=3306;Database=database-name;Uid=username;Pwd=password;" providerName="MySql.Data.MySqlClient" />

3. In your code you can then open a connection to your database:

var db = Database.Open("Any-name");


If you get the error message "Unable to find the requested .Net Framework Data Provider. It may not be installed." then you will also need to add some extra lines to web.config.

<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory,MySql.Data" />

Related Posts

Intermittent "Unable to read data from the transport connection: net_io_connectionclosed" errors

by John Avis | May 6, 2020

If you are having intermittent problems sending email in .NET using System.Net.Mail consider switching libraries.

Disabling request validation in ASP.NET Web Pages

by John Avis | November 27, 2019

How to avoid A potentially dangerous Request.Form value was detected from the client errors when developing in ASP.NET Web Pages.

500 Internal Server Error after migrating from IIS 7.5 to IIS 10

by John Avis | November 4, 2019

As support ends for Microsoft Windows Server 2008 I have recently gone through migrating some websites to a new server running Windows Server 2016 and IIS 10 but some of the websites did not work.


Tony Dunsworth

by Tony Dunsworth | August 2, 2013

Would this work with the same set up for an Oracle database using ODP.NET dll's?


John Avis

by John Avis | August 2, 2013

You can connect to an Oracle database (or any ADO.NET provider) in the same way with WebPages. Just add your connection string.


Leave a Comment



...random postings about web development and programming, Internet, computers and electronics topics.

I recommend ASPnix for web hosting and Crazy Domains for domain registration.


Get the latest posts delivered to your inbox.