Click here to Skip to main content
6,593,923 members and growing! (12,965 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » LINQ » General     Beginner License: The Code Project Open License (CPOL)

CRUD Operations using LINQ Entities

By Shivprasad koirala

CRUD operations using LINQ Entities
C#, .NET (.NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0), ASP.NET, SQL Server, Visual Studio (VS.NET2003, VS2005, VS2008, VS2010), LINQ, Architect
Version:3 (See All)
Posted:10 Jul 2009
Updated:11 Jul 2009
Views:6,142
Bookmarked:29 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
8 votes for this article.
Popularity: 4.06 Rating: 4.50 out of 5

1

2
1 vote, 12.5%
3
1 vote, 12.5%
4
6 votes, 75.0%
5

Table of Contents

Introduction and Goal

This is a pretty simple tutorial dedicated to LINQ newbies who want to learn how to do CRUD operations using LINQ entities. I am sure many experienced LINQ players would criticize me for such a mild article. One of the biggest catches which I found is the in-memory update service by LINQ, which I think for any LINQ newbie is a must to understand.

So we will start with an understanding of the differences between in-memory updates and physical commits and then we will go deep into the code for each database operation. Again this article is one of those small sprints which I need to run so that I can complete the huge LINQ FAQ project.

Watch my 500 videos dedicated to Microsoft technologies here.

Screen shot of what we are going to talk about

Still New to LINQ - Below are Some Real Quick Starters

  • Are you a complete newbie? Read this.
  • Do you want to define 1-* and *-1 using LINQ? Read this.
  • Issues of multiple trips handled in this article? Read this.
  • Do not know how to call stored procedures using LINQ? Read this.

LINQ In-memory Commits and Physical Commits

Entity objects form the base of LINQ technologies. So when any data is submitted to database, it goes through the LINQ objects. Database operations are done through ‘DataContext’ class. As said previously, entities form the base of LINQ, so all the data is sent to these entities first and then it's routed to the actual physical database. Due to this nature of working database commits is a two step process. The first step is in-memory and final step is physical commits.
In order to do in-memory operation ‘DataContext’ has provided ‘DeleteOnSubmit’ and ‘InsertOnSubmit’ methods. When we call these methods from the ‘DataContext’ class, they add and update data in the entity objects memory. Please note these methods do not change / add new data in the actual database.

Once we are done with the in-memory operations and we want to send all the updates to the database, we need to call ‘SubmitChanges()’ method. This method finally commits data into the physical database.

So let’s consider a customer table (customerid, customercode and customername) and see how we can do the in-memory and physical commit operations.

Step 1: Create the Entity Customer Class

So as a first step, we create the entity of customer class as shown in the below code snippet.

[Table(Name = "Customer")]
public class clsCustomerEntity
{
private int _CustomerId;
private string _CustomerCode;
private string _CustomerName;

[Column(DbType = "nvarchar(50)")]
public string CustomerCode
{
set
{
_CustomerCode = value;
}
get
{
return _CustomerCode;
}
}
[Column(DbType = "nvarchar(50)")]
public string CustomerName
{
set
{
_CustomerName = value;
}
get
{
return _CustomerName;
}
}
[Column(DbType = "int", IsPrimaryKey = true,IsDbGenerated=true)]
public int CustomerId
{
set
{
_CustomerId = value;
}
get
{
return _CustomerId;
}
}
}

Step 2: Create using LINQ

Create Data Context

So the first thing is to create a ‘datacontext’ object using the connection string.

DataContext objContext = new DataContext(strConnectionString);

Set the Data for Insert

Once you create the connection using the ‘DataContext’ object, the next step is to create the customer entity object and set the data to the object properties.

clsCustomerEntity objCustomerData = new clsCustomerEntity();
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerName = txtCustomerName.Text;

Do an In-memory Update

We then do an in-memory update in entity objects itself using ‘InsertOnSubmit’ method.

objContext.GetTable<clsCustomerEntity>().InsertOnSubmit(objCustomerData);

Do the Final Physical Commit

Finally we do a physical commit to the actual database. Please note until we call ‘SubmitChanges()’, data is not finally committed to the database.

objContext.SubmitChanges();

The Final Create LINQ Code

Below is the final LINQ code put together:

DataContext objContext = new DataContext(strConnectionString);
clsCustomerEntity objCustomerData = new clsCustomerEntity();
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerName = txtCustomerName.Text;
objContext.GetTable<clsCustomerEntity>().InsertOnSubmit(objCustomerData);
objContext.SubmitChanges();

Step 3: Update using LINQ

So let’s take the next database operation, i.e. update.

Create Data Context

As usual we first need to create a ‘datacontext’ object using the connection string as discussed in the create step:

DataContext objContext = new DataContext(strConnectionString);

Select the Customer LINQ Object Which we want to Update

Get the LINQ object using LINQ query which we want to update:

var MyQuery = from objCustomer in objContext.GetTable<clsCustomerEntity>()
where objCustomer.CustomerId == Convert.ToInt16(txtCustomerId.Text)
select objCustomer;

Finally Set New Values and Update Data to Physical Database

Do the updates and call ‘SubmitChanges()’ to do the final update.

clsCustomerEntity objCustomerData = 
	(clsCustomerEntity)MyQuery.First<clsCustomerEntity>();
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerName = txtCustomerName.Text;
objContext.SubmitChanges();

The Final Code of LINQ Update

Below is what the final LINQ update query looks like.

DataContext objContext = new DataContext(strConnectionString);
var MyQuery = from objCustomer in objContext.GetTable<clsCustomerEntity>()
where objCustomer.CustomerId == Convert.ToInt16(txtCustomerId.Text)
select objCustomer;
clsCustomerEntity objCustomerData = 
	(clsCustomerEntity)MyQuery.First<clsCustomerEntity>();
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerName = txtCustomerName.Text;
objContext.SubmitChanges();

Step 4: Delete using LINQ

Let’s take the next database operation delete.

DeleteOnSubmit

We will not be going through the previous steps like creating data context and selecting LINQ object. Both of them are explained in the previous section. To delete the object from in-memory, we need to call ‘DeleteOnSubmit()’ and to delete from final database, we need use ‘SubmitChanges()’.

objContext.GetTable<clsCustomerEntity>().DeleteOnSubmit(objCustomerData);
objContext.SubmitChanges();

Step 5: Self Explanatory LINQ Select and Read

Now in the final step, selecting and reading the LINQ object by criteria. Below is the code snippet which shows how to fire the LINQ query and set the object value to the ASP.NET UI.

DataContext objContext = new DataContext(strConnectionString);

var MyQuery = from objCustomer in objContext.GetTable<clsCustomerEntity>()
where objCustomer.CustomerId == Convert.ToInt16(txtCustomerId.Text)
select objCustomer;

clsCustomerEntity objCustomerData = 
	(clsCustomerEntity)MyQuery.First<clsCustomerEntity>();
txtCustomerCode.Text = objCustomerData.CustomerCode;
txtCustomerName.Text = objCustomerData.CustomerName;

The LINQ CRUD Code

You can download the complete CRUD source code from here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shivprasad koirala


Member
He thinks he was born for only one mission and thats technology.Keeping this mission in mind he established www.questpond.com where he has uploaded 500 videos on WCF,WPF,WWF,Silverlight,Design pattern, FPA , UML , Projects etc. He is also actively involved in RFC which is a financial open source made in C#. It has modules like accounting , invoicing , purchase , stocks etc.
Occupation: Architect
Company: http://www.questpond.com
Location: India India

Other popular LINQ articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
GeneralDoes it work with MySQL PinmemberS. Kolic23:58 30 Aug '09  
QuestionUpdate without reselect back the record PinmemberJason Law20:48 21 Jul '09  
GeneralGood One PinmvpAbhijit Jana13:20 14 Jul '09  
GeneralIt's nice PinmemberMd. Marufuzzaman8:05 11 Jul '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 11 Jul 2009
Editor: Deeksha Shenoy
Copyright 2009 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project