SIGN UP MEMBER LOGIN:    
ARTICLE

Using LINQ to SQL Class

Posted by Dhananjay Kumar Articles | LINQ with C# May 07, 2010
In this article, I am going to show you how we can perform various operations using LINQ to SQL.
Reader Level:
Download Files:
 

In this article, I am going to show you how we can perform various operations using LINQ to SQL. 

1.gif

Database description

Let us say, I have created a database called ILPTrainee. This table got only one table with below structure 

2.gif

EmpId is primary key here. 

For our explanation, I have put few records in the table. So table with records is as below 

3.gif

Using LINQ to SQL Class 
  1. Create a new project of type class library. 
  2. Right click on the project and add new item and select LINQ to SQL Class from Data tab. 
  3. Select Server Explorer. Then Server Explorer will get open. Click on Data connection and Add new connection. 
  4. In Server name give name of your database server and from drop down select the database.
  5. Once you are done with above steps, you can see a dbml file got generated in solution explorer. 
Follow the diagrams below, in order left to right and top to down. 

4.gif

5.gif

LINQ to SQL class is an ORM which creates a class representing your table from the database.  It will create a datacontext class.  We will apply query against generated data context class. 

TraineeModels class is representation of TraineeModel table.

Now querying 

To perform query add a new class in the same class library project. Make this class as static. Add various static methods that will be performing different types of query. 

Query 1 # retrieving all the records from table 

6.gif

Explanation 
  1. I created instance of Data Context class. 
  2. I applied simple LINQ query to retrieve all the records from the table TraineeModels  in data context. 
Query 2 # retrieving selected records from table 

7.gif

Explanation 
  1. I created instance of Data Context class. 
  2. I applied simple LINQ query to retrieve all the records from the table TraineeModels in data context. 
  3. I applied where clause to filter the data. 
Query 3 # inserting a single record 

8.gif

Explanation 
  1. I created instance of Data Context class. 
  2. Input parameter to this method is object of TraineeModel class. 
  3. I am using InsertOnSubmit method on the datacontext class to insert one record. 
  4. Then finally, I am calling the submitchanges to commit the database on datacontext. 
Query 4 # Updating a Record

9.gif

Explanation 
  1. I created instance of Data Context class. 
  2. Input parameter to this method is object of TraineeModel class. 
  3. I am retrieving the object to be modified using where clause. 
  4. After modification, calling the submitchanges on data context. 
Query 5 # Deleting a Record

10.gif

Explanation 
  1. I created instance of Data Context class. 
  2. Input parameter to this method is empid as string to be deleted.  
  3. I am retrieving the object to be deleted using where clause. 
  4. After deletion, calling the submitchanges on data context. 
Query 6 # Adding List of Records  

11.gif

Explanation 

1. I created instance of Data Context class. 
2. Input parameter to this method is List of TraineeModels to be inserted.  
3. I am inserting the records using InsertAllOnSubmit method on data context class. 
4. After insertion, calling the submitchanges on data context. 

Query 7 # Deleting List of Records  

12.gif

Explanation 
  1. I created instance of Data Context class. 
  2. Input parameter to this method is List of TraineeModels to be deletd.  
  3. I am deleting the records using deleteAllOnSubmit method on data context class. 
  4. After insertion, calling the submitchanges on data context. 
Up to this step, I have written all possible LINQ query to be used for CRUD operation.  Now to use this query just call the methods with class name. 

For your reference, whole code is given below. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataOperationsLibrary
{
    public static  class CRUDRepository
    {
        public static List<TraineeModel> GetTrainees()
        {
           DataClasses1DataContext context = new DataClasses1DataContext();
           var result = from r in context.TraineeModels select r;
           return result.ToList();
        }
        public TraineeModel GetSelectedTrainee(string EmpId)
        {
            DataClasses1DataContext context = new DataClasses1DataContext();
            TraineeModel traineeResult = (from r in context.TraineeModels where r.EmpId == EmpId
                                          select r).First();
            return traineeResult;
        }
        public static bool AddTrainee(TraineeModel  trainee)
        {
            try
            {
                DataClasses1DataContext context = new DataClasses1DataContext();
                context.TraineeModels.InsertOnSubmit(trainee);
                context.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static bool DeleteTrainee(string empID)
        {
            try
            {
                DataClasses1DataContext context = new DataClasses1DataContext();
                TraineeModel  obj = (from r in context.TraineeModels
                                          where r.EmpId.Contains(empID)
                                          select r).First();
                if (obj != null)
                {
                    context.TraineeModels .DeleteOnSubmit(obj);
                    context.SubmitChanges();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
        public static bool UpdateTrainee(TraineeModel  trainee)
        {
            try
            {
                DataClasses1DataContext context = new DataClasses1DataContext();
                TraineeModel  res = (from r in context.TraineeModels
                                          where r.EmpId.Contains(trainee.EmpId)
                                          select r
                                          ).First();
                res.EmpName = trainee.EmpName;
                res.Expertise = trainee.Expertise;
                res.Native = trainee.Native;
                context.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static bool AddTrainees(List<TraineeModel> lstTrainee)
        {
            try
            {
                DataClasses1DataContext context = new DataClasses1DataContext();
                context.TraineeModels.InsertAllOnSubmit(lstTrainee);
                context.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static bool DeleteTrainees(List<TraineeModel> lstTrainee)
        {
            try
            {
                DataClasses1DataContext context = new DataClasses1DataContext();
                context.TraineeModels.DeleteAllOnSubmit(lstTrainee);
                context.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

I hope, this post was useful. Thanks for reading. Happy Coding. 

Login to add your contents and source code to this article
Article Extensions
Contents added by Malik Muhammad Fraz on May 26, 2012
share this article :
post comment
 

Firtst of all, thanks for writing this. I was looking for something like this. I have been developing a asp.net c# webforms application. I currently use linq2SQL. All my linq calls are in the codebehind. I wanted to take them out and place them some place centrel, as I have quite a few linq statements that are used in other forms and instead of copying and pasting them all over the place, just call them from from a library. In VB, I created a BO and DAL class and used data access blocks to perfom those kinds of operations, passing form fields to properties, etc. Now, with linq, I want to pass the same along to static class methods, returning the data or Inserting, Updating and deleting data. I understand most of your code. I have ONE question: how does this (2.Input parameter to this method is object of TraineeModel class) happen? Do I insert the form values into the "TraineeModel class", for instance, then call the insert/update method like "UpdateTrainee(TraineeModel)", passing the class to the static method?

Posted by Loften Pierce Dec 11, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor