Skip to main content

Beginning LinQ To SQL In C#.NET

In this tutorial, I will discuss about basic linq to sql overview, then how to get started very quickly with its usage on our C#.NET based applications(This can be used in both desktop and web applications in the exactly same way). Besides, I will also discuss about using 'select' query in linq to retrieve data and also traverse through the query results(in case of multiple result objects). To understand this tutorial properly, You should have handy knowledge on c# and also have visual studio 2008+(.NET Framework 3.0+ ) to successfully able to run LINQ To SQL examples.

What Is LINQ To SQL?

Full meaning of LINQ is 'Language Integrated Query', which replaces the traditional sql query execution process. Moreover, it doesn't only applicable to manipulate database results, but it can also be used to manipulates array/list collections. LinQ was released as part of the .NET framework 3.0 and can be used from languages supported by .NET framework like C#, VB etc. The term 'LINQ To SQL' refers to the technology by which we can use LINQ for access SQL Databases. Here in this tutorial, I will show step by step ways to get started with LINQ To SQL programming with C#.

Mapping LINQ To SQL Class From SQL Server Database:

First step to be able to use LinQ on our SQL database, we will need to define a way, by which .NET can recognize the database as Classes/Objects, so we will need to map the database tables/stored procedures to LinQ to SQL classes. To accomplish this task successfully, first open your project in the solution explorer, right click->add->new item, in the 'data' categories, there is a type named 'LINQ To SQL Classes'. Select that. We will get a .dbml file created along with designer interface.

The designer interface has two part, one for dragging tables from server explorer(to create classes from tables automatically), another is for methods where we can drag stored procedures etc. After dragging all classes from server explorer, we are done. Here is a sample db structure that we will be using on the way of this tutorial:
Linq To Sql Class In DBML Design

Select Data Using LinQ To SQL:

After we make the dbml files appropriately, its very simple to get started our actually implementation in c# code. Most interesting thing is, we will be using sql query like syntax right from the c# code for getting database results. Suppose, we are trying to validate a user against a given username/password from database. Here is a sample codes of a function for such purpose:
1public bool IsValidUser(string userName, string passWord)
2{
3DBNameDataContext myDB = new DBNameDataContext();
4var userResults = from u in myDB.Users
5                         where u.Username == userName
6                         && u.Password == passWord
7                         select u;
8return Enumerable.Count(userResults) > 0;
9}
You can see, the syntax is much like sql, but not exactly same though. First, when you create a new dbml file with name 'DBName.dbml', there is created a corresponding DataContext class in .net and named something like 'DBNameDataContext' (These DataContext classes are now responsible for .NET To Database communications) . In the linq query syntax, this object will be used to present the database.
Next, whenever we write something like "from u in myDB.Users" visual studio automatically treat 'u' as a object of User class, that actually represents database's 'users' table(you will might also notice if your database table contains plural form like 'users', it automatically makes it as singular when creating the linq to sql class like 'User', though table name used in the query will still be plural).
Next, notice one of the most useful advantage of LINQ, if you make any kind of data type mistake in your code, you will be notified immediately while compiling your project. This will saves lots of your debugging time and lessen the db errors at the same time. its possible here as now all you are using are acting like a .NET class, so its simply validating the property's data type. Of course, you will have to remember that, if you change your db structure/column data type etc later on, you should have to drag the tables from server explorer to dbml once again to reflect your db changes to the linq to sql classes.
Next, Note the result is assign to a variable of type 'var'. This data type is also new from .NET framework 3.0 and used to represent data with dynamic types. That means, here any kind of data returned from the linq query will be assigned to that variable and you will have to just cast that to the appropriate data type.
Next, "Enumerable.Count", this function count the number of rows(Or number of objects) returned by the query. You can use this function on 'var' type result object without need of casting it to any intermediate form.

Select Operation Without SQL Syntax in LinQ:

The above example showed how to use LinQ To SQL syntax for querying database for retrieve data. However, there is alternative simple ways also for avoid using query like syntax by using integrated 'Where' method. Here is a simple code example to accomplish that:

01public bool IsValidUser(string userName, string passWord)
02{
03       DBNameDataContext myDB = new DBNameDataContext();
04       List<User> users = myDB.Users.Where(u => u.Username == userName && u.Password==passWord);
05       if(users.Count>0)
06       {
07             return true;
08       }
09       return false;
10}

Retrieve A Single Row With LinQ:

On the above example, we have learned to execute a sql like statement. However, LINQ provides much more flexibility than that. Like, if you need a single item/row from database table, it can be done very easily. Here is a code sample for such cases:

1public User GetUser(string userName)
2{
3     DBNameDataContext myDB = new DBNameDataContext();
4     User user = myDB.Users.Single(u, u.UserName=>userName);
5     return user;
6}
The above example will return a single record from database table. In the "u.UserName=>userName" part, you can mention any column name you want to be validated.

'Foreach' Loop Through All LinQ To SQL Returned Results:

In case, when LinQ query returns multiple results, we often need to traverse through all the result rows(here all LinQ objects) and process in some way. It can be done very easily with a foreach loop. Although for loop also can be used, however foreach is much better in performance(to know details, you can refer to my for vs foreach article). here is the code samples for using the foreach loop for traversing through all result objects:

1foreach(User user in userResults)
2{
3    //checking the result as like object
4    if(user.Role == 'admin')
5     {
6         //do whatever you need
7     }
8}

Comments

Popular posts from this blog

FlexBox (combobox+json +Paging)

FlexBox Visit the FlexBox Home Page FlexBox  is a jQuery plugin that is intended to be a very flexible replacement for html textboxes and dropdowns, optionally using ajax to retrieve and bind JSON data. It can be used as a: ComboBox, with optional per-result html templates Suggest box, like Google's search Data-driven type-ahead input box It supports: Auto-completion using local (JSON) or remote (JSON via ajax) data Skinning via css Flexible paging Configurable client-side caching Much more... (see Configuration Options in the documentation) Screenshotflex More demos and code examples

ASP .NET - XML Files

An XML File Here is an XML file named "countries.xml": <?xml version="1.0" encoding="ISO-8859-1"?> <countries> <country>   <text>Norway</text>   <value>N</value> </country> <country>   <text>Sweden</text>   <value>S</value> </country> <country>   <text>France</text>   <value>F</value> </country> <country>   <text>Italy</text>   <value>I</value> </country> </countries> Bind a DataSet to a List Control First, import the "System.Data" namespace. We need this namespace to work with DataSet objects. Include the following directive at the top of an .aspx page: <%@ Import Namespace="System.Data" %> Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is first loaded: <script runat="server"> sub Page_Load if Not Page.IsPos...

SQL JOINS &UNION

SQL JOIN The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables. Tables in a database are often related to each other with keys. A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table. Look at the "Persons" table: P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger Note that the "P_Id" column is the primary key in the "Persons" table. This means that  no  two rows can have the same P_Id. The P_Id distinguishes two persons even if they have the same name. Next, we have the "Orders" table: O_Id OrderNo P_Id 1 77895 3 2 44678 3 3 22456 1 4 24562 1 5 34764 15 Note that the "O_...