linq mysql asp net

Upload: bc2255

Post on 30-May-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Linq Mysql ASP Net

    1/4

    rimary Objects - Using MySQL and LINQ to SQL in C# ASP .NET

    home | articles | site map | contacts

    Using MySQL and LI NQ to SQL in C# ASP .NET

    More C# ASP .NET

    Articles by Primary Objects

    enter email address

    Share

    Introduction

    LINQ is one of the most popular Microsoft technologies for reading and writing to SQL Server databases. LINQ to SQL builds uponLINQ technology to allow working with business objects, generated from the database tables. Tranditionally, LINQ to SQL iscompatible with SQL Server databases and does not easily support other database formats. Since LINQ is a leap forward fordevelopers accessing databases, it's important to be able to use LINQ with other popular database formats as well. This article

    describes how to use LINQ to SQL with a MySQL database in C# ASP .NET.

    The Old Way of Doing Things

    Prior to LINQ, working with databases from C# ASP .NET web applicationsinvolved handling database connections, SQLConnection and SqlCommandobjects, and working with data readers. While this technique provided a lowerlevel of approach to database interactivity from C#, it was also more prone toerror (ie. leaving connections open, reading wrongly-typed database columnparameters, etc). You may have used the following code to access a database:

    using System;using System.Data;using MySql.Data.MySqlClient;

    MySqlConnection MyConnection = null;MySqlDataReader MyReader = null;

    // Create the SQL connection.MyConnection = new MySqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI"))MyConnection.Open();

    ttp://www.primaryobjects.com/CMS/Article100.aspx (1 of 6) [1/21/2010 8:03:22 AM]

    Subscribe

    http://www.primaryobjects.com/default.aspxhttp://www.primaryobjects.com/ArticleDirectory.aspxhttp://www.primaryobjects.com/sitemap.aspxhttp://www.primaryobjects.com/contact.aspxhttp://www.primaryobjects.com/ArticleDirectory.aspxhttp://www.primaryobjects.com/ArticleDirectory.aspxhttp://www.addthis.com/bookmark.php?v=250&pub=surfer6http://flickr.com/photos/lapineite/2193187190/http://www.addthis.com/bookmark.php?v=250&pub=surfer6http://www.primaryobjects.com/ArticleDirectory.aspxhttp://www.primaryobjects.com/ArticleDirectory.aspxhttp://feeds.feedburner.com/PrimaryObjectshttp://www.primaryobjects.com/contact.aspxhttp://www.primaryobjects.com/contact.aspxhttp://www.primaryobjects.com/clients/default.aspxhttp://www.primaryobjects.com/services.aspxhttp://www.primaryobjects.com/about.aspxhttp://www.primaryobjects.com/contact.aspxhttp://www.primaryobjects.com/sitemap.aspxhttp://www.primaryobjects.com/ArticleDirectory.aspxhttp://www.primaryobjects.com/default.aspxhttp://www.primaryobjects.com/
  • 8/14/2019 Linq Mysql ASP Net

    2/4

  • 8/14/2019 Linq Mysql ASP Net

    3/4

    rimary Objects - Using MySQL and LINQ to SQL in C# ASP .NET

    {}

    5 . Finally, delete the constructors from the DataContext class and add the following constructor:

    public PeopleDataContext(): base(new MySqlConnection(ConfigurationManager.ConnectionStrings["people"].ConnectionString))

    {}

    This new constructor allows you to use the data context class without having to worry about the connection string each time. Of

    course, in your web.config file you'll need to add the following connection string with your own database settings:

    With the MySQL data context class created, you now have a set of LINQ to SQL business objects that you can use to read and write toyour MySQL database with LINQ queries.

    Reading a MySQL Table with LINQ

    One of the first tasks you'll want to perform is to read data from the MySQL table, such as in the case of populating a GridView controlwith the information from the table. You could do so with the following code:

    public static List GetPeople(){

    using (PeopleDataContext context = new PeopleDataContext()){

    var results = from s in context.Personorderby s.LastName ascendingselect s;

    return results.Take(25).ToList();}

    }

    protected void Page_Load(object sender, EventArgs e){

    if (!IsPostBack){

    lstMyGridView.DataSource = GetPeople();lstMyGridView.DataBind();

    }}

    The above LINQ query in your MySQL database would result in the following SQL language:SELECT ID, FIRSTNAME, LASTNAME, AGE FROM PERSON ORDER BY LASTNAME DESC LIMIT 0,25

    You can actually display the query language in the Debug Console, Output window, or other streams via the context.Log property. For

    example, context.Log = new DebuggerWriter().

    Inserting into a MySQL Table with LINQ

    Adding records to a MySQL table with LINQ2SQL can also be done with the generated data context class. Note in the code below, we'repassing in a LINQ to SQL business object, generated by DbLinq from the MySQL table, just as you would with an SQL Server database:

    public static Person AddPerson(Person person){

    using (PeopleDataContext context = new PeopleDataContext()){

    context.Person.InsertOnSubmit(person);context.SubmitChanges();

    ttp://www.primaryobjects.com/CMS/Article100.aspx (3 of 6) [1/21/2010 8:03:22 AM]

    http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11
  • 8/14/2019 Linq Mysql ASP Net

    4/4

    rimary Objects - Using MySQL and LINQ to SQL in C# ASP .NET

    return person;}

    }

    protected void btnAdd_Click(object sender, EventArgs e){

    // Create a LINQ to SQL class to fill the properties.Person person = new Person();person.FirstName = txtFirstName.Text;person.LastName = txtLastName.Text;person.Age = Convert.ToInt32(txtAge.Text);

    person = AddPerson(person);}

    A Simple Searching Query with LI NQ to SQL and M ySQL

    Since LINQ is being used to access the MySQL database from C# ASP .NET, we have a large variety of query types that we can executewhen retrieving data. Below is an example of a query to select people by keyword:

    public static List GetPeople(string keywords){

    using (PeopleDataContext context = new PeopleDataContext()){

    var results = from s in context.Personwhere s.FirstName.ToLower().Contains(keywords.ToLower()) ||

    s.LastName.ToLower().Contains(keywords.ToLower())orderby s.LastName ascendingselect s;

    return results.Take(25).ToList();}

    }

    protected void btnSearch_Click(object sender, EventArgs e){

    lstMyGridView.DataSource = GetPeople(txtKeywords.Text);lstMyGridView.DataBind();

    }

    Conclusion

    While LINQ to SQL is traditionally made to generate SQL Server business objects and access SQL Server databases from C# ASP .NET, we can also use it to access other popular databases, including MySQL, through the help of a data context generation tool,such as DbLinq. Utilizing LINQ and LINQ to SQL to access database tables provides for strongly-typed database column access andeasier handling of database connectivity. By using LINQ and LINQ to SQL in your MySQL database access layer, you can help makeyour C# ASP .NET web applications more robust, expandable, and less prone to error.

    About the Author

    This article was written by Kory Becker, founder and chief developer of Primary Objects, a software and web applicationdevelopment company. You can contact Primary Objects regarding your software development needs at http://www.primaryobjects.com

    Pos t comm ent >

    ttp://www.primaryobjects.com/CMS/Article100.aspx (4 of 6) [1/21/2010 8:03:22 AM]

    http://www.primaryobjects.com/http://www.primaryobjects.com/