• Home >> Net C# >>  LINQ
  • introduction to linq, part 3: linq to sql


  • Rating : Excellent[1]   Very Good[0]   Average[0]   Below Average[0]   Poor[0]
  • Pub Date: 10/9/2008
  • admin [ View Profile ]

  • Abstract
  • In the previous articles of the series, I have introduced LINQ to Objects and LINQ to XML. LINQ stands for Language-INtegrated Queries and basically makes queries first citizens of languages such as C# and VB.NET. The topic of this article is another component of LINQ, called LINQ to SQL; it provides a run-time environment that enables the managing of relational databases as objects, with great support for querying.

  • Introduction
  •  Sponsored Links
  •  

     

    linq to sql is actually a sub-component of linq to ado.net, which includes:

    in this article, i will give you an introduction to linq to sql, which covers some basic elements. notice that you need sql server 2005 installed and the ucl.mdf database to run the demo application provided with this article. i also recommend first reading about linq to objects first.

    decorating attributes

    objects are linked to relational data by decorating normal classes with attributes. two of the most important attributes are table and column.

    the table attribute is used to decorate the class. one of its properties is name; it is used to specify the name of the table to which an object of the class is linked. if the name property is missing, the name of the class will be used for the name of the table. a class decorated with the table attribute is called an entity class, and an instance of an entity class is called an entity. only entities are stored in a database.

    the column attribute is used to decorate fields or properties of an entity class, to associate them with columns of a table. the column attribute has also several properties, one of them being the name property. as in the case of the name property of table, it is used to specify the field in the table to which the field or property of the entity class is matched. if the property is not specified, the name of the field or property of the entity class will be assumed as the name of the field in the table.

    in the previous two articles, i have performed queries on various sequences with winners of the uefa champions league. i will do the same in this article. my former winner class, in its simplest form, looked like this:

    public class winner
    {
    public string name { get; set; }

    public string country { get; set; }

    public int year { get; set; }
    }

    in this article, you will associate this class with a table from an sql server database. the database is available for download, and is called ucl.mdb. it has four tables, but the first you will take into consideration is called winners. this table has three fields:

    • year, an integer, the primary key for the table
    • country, a varchar, the country of the winner team
    • name, a varchar, the name of the team

    to transform the normal winner class above in an entity class mapped on this table, it has to be decorated with the table and column attributes:

    [table(name = "winners")]
    public class winner
    {
    [column]
    public string name { get; set; }

    [column]
    public string country { get; set; }

    [column(isprimarykey = true)]
    public int year { get; set; }
    }

    the table.name property specifies that the entity class winner is mapped on the winners table in the database. the column attributes specifies that the name, country, and year properties are mapped on columns with the same name from the table. in addition, the column.isprimarykey property being set to true for year, indicates that this column is the primary key in the table.

    the datacontext and table classes

    the channel through which objects are retrieved from the database, and changes are submitted to the database, is the class called datacontext. it can be used like an ado.net connection. the overloaded constructor takes either a connection or a string connection. what this class does is translate requests for objects into sql queries and assemble the objects from the result of queries.

    tables in a relational database are represented as table collections (which implements interfaces such as iqueryable and ienumerable). datacontext has a method called gettable<>(); it represents a potential interaction with the table of view. the query is not actually executed until iteration over the result is performed. the type parameter of gettable() identifies the table in the database.

    retrieving the winners from the database can be done in the following way:

    public void printwinners()
    {
    // creates a data context that takes the path of the database
    datacontext dc = new datacontext(@"c:\program files\
    microsoft sql server\mssql.1\mssql\data\ucl.mdf");

    // retrieves a table of winner
    table<winner> winners = dc.gettable<winner>();

    // creates a sequence of winners ordered descending by the
    // winning year
    var result = from w in winners
    orderby w.year descending
    select w;

    // prints the sequence of winners
    foreach (var w in result)
    {
    console.writeline("{0} {1}, {2}",
    w.year, w.name, w.country);
    }
    }

    running the code prints out:

    2006 barcelona, spain
    2005 liverpool, england
    2004 fc porto, portugal
    2003 ac milan, italy
    2002 real madrid, spain
    2001 bayern munchen, germany
    2000 real madrid, spain
    1999 manchester utd., england
    1998 real madrid, spain
    1997 borussia dortmund, germany
    1996 juventus, italy
    1995 afc ajax, netherlands
    1994 ac milan, italy
    1993 olympique de marseille, france
    note: in the code above, the path to the database is hard-coded and corresponds to the location on my machine. if you run the sample application, make sure you use the correct path on your machine.

    when first iterating over the result of the query, the datacontext translates the query into an sql statement:

    select [t0].[country], [t0].[name], [t0].[year]
    from [winners] as [t0]
    order by [t0].[year] asc

    as i said earlier, datacontext allows you to submit changes to the database. in the example, you first need to make the changes to the collection of winners, and then call the method submitchanges(). to add a new winner, you can do this:

    public void addwinner()
    {
    // creates a data context that takes the path of the database
    datacontext dc = new datacontext(@"c:\program files\
    microsoft sql server\mssql.1\mssql\data\ucl.mdf");

    // retrieves a table of winner
    table<winner> winners = dc.gettable<winner>();

    // adds a new winner to the table
    winners.add(new winner { name = "ac milan",
    country = "italy",
    year = 2007});

    // submites the changes
    dc.submitchanges();
    }

    if you look into the database after running this function, or if you call printwinners(), you will see that the new entry was added to the winners table.

    updating or deleting can be performed in the same way. the following example removes all the winners from italy:

    public void deletewinners()
    {
    // creates a data context that takes the path of the database
    datacontext dc =
    new datacontext(@"c:\program files\microsoft sql server\
    mssql.1\mssql\data\ucl.mdf");

    // retrieves a table of winner
    table<winner> winners = dc.gettable<winner>();

    // remove a sequence of winners
    winners.removeall(from w in winners
    where w.country == "italy"
    select w);

    // submites the changes
    dc.submitchanges();
    }



  •  

  • RATE THIS ARTICLE :
  •  
    • Latest Comments:
      • Add a comment
      • Title:
      • Comment
      •  
    Other popular LINQ articles:
    • LINQ to SQL Serialization

      I am a huge fan of LINQ to SQL feature of the .NET Framework 3.5. If you don't know what LINQ to SQL is, please read the white paper here.I like the way in which it makes database coding simple and easy. Developers do not have to use different programming models (CLR functions and SQL Stored Procedu

    • LINQ in Multi-tier Applications

      If you had the chance to work with LINQ, the latest Object Relational Mapping tool (ORM) added to the .NET 3.5 platform, then you understand how LINQ maps your database structure into several classes in your application. It creates for each table an entity class that has its properties mapped to the

    • LINQ Challenges and SQL Server Compact Edition

      ContentsLINQ to SQLGrounds for Determination (The Sample)LINQ and SQL Server Compact EditionWorking with Enumerations in LINQ to SQLField Subset Challenges with LINQ to SQLChange Tracking Challenges with LINQ to SQLDisconnected Challenges with LINQ to SQLPre-fetching Challenges with LINQ to SQLOther

    • how to: linq to sql transformation

      The v3.5 release of the .NET framework includes a significant number of new and enhanced technologies. LINQ (Language Integrated Query) is, in my opinion, the most significant new technology in the v3.5 release. Microsoft has implemented a set of libraries to transform LINQ expression trees to SQL s

    • linq to csv library

      ContentsRequirementsInstallationQuick StartWrite OverloadsRead OverloadsDeferred ReadingCsvFileDescriptionCsvColumn AttributeError HandlingThis library makes it easy to use CSV files with LINQ queries. Its features include:Follows the most common rules for CSV files. Correctly handles data fields th

    • Implementing a Left Join with LINQ

      Oddly enough, LINQ doesn't define keywords for cross join, left join, or right join. As part of the LINQ grammar, you get join and group join. Joins can be equijoins or non-equijoins. An equijoin uses the join keyword and non-equal joins are contrived using where clauses. However, left, right, and c

    • Working with Range Variables and Let Statements in LINQ

      Complicated things seem intuitively simple when complexity is cleverly hidden in the open. LINQ is a query language that at its basic is pretty simple to learn to use, but there is a lot of meaning in all of the aspects of a query. Understanding these cleverly hidden meanings will help you get beyon

    • Introduction to LINQ, Part 1: LINQ to Objects

      Perhaps the most important new feature to the next version of Visual Studio, for now code-named 'Orcas,' is the release of LINQ, which stands for Language INtegrated Queries. LINQ is actually a set of operators, called standard query operators, that allow the querying of any .NET sequence. LINQ come

    • How To LINQ To SQL: Part III

      This article is the third in a series outlining how to translate LINQ expression trees to SQL statements that can be executed against multiple RDBMS systems and not just Microsoft's SQL Server offerings. The articles will also illustrate how to:Correctly and comprehensively translate binary and unar

    • SqlLinq: Taking LINQ to SQL in the Other Direction

      I've wanted to write an application that would allow me to execute queries against my music collection for some time now. Having been burning my CDs to MP3 and WMA for some years now, it contains thousands of songs, and I've been wanting something a bit more robust than what most music players I've

    About Us |Contact us |Site Map |Csharp |Visual C / C++ |Visual basic |Java |SQL |Linux / Unix |Ajax
    ©2007-2018 CodeCoolest.com. Ptolive.cn Asp.net source code All Rights Reserved.