Skip to main content

LinQ Database Update Operations In C#


Recently, I have discussed about getting started linq to sql in c#.net. That articles also covered for creating select query for retrieving both single and multiple results. Today, in this tutorial, I will try to give some more examples on other types of database operations, that writes/updates the database. These will cover writing and executing 'Update'/'Insert'/'Delete' query in the proper way. Please use the database structure given below, if you want to try the following examples directly. I am assuming, you already know how to create dbml/linq to sql classes:





Sample Linq To SQL Dbml
Example DBML To be used In this tutorial

Insert Data With Linq:

Being LinQ as an ORM, its quite easy and sql syntax free way to insert data using LinQ. We just need to create a new object of corresponding database table type, then add it to the DataContext object and then commit the changes. Here is a small block of c# code samples to create new 'User' linq to sql class(Representing 'Users' Table in Database) and add it to 'UsersDataContext' class(Represents the database) and commit the changes to original database by 'SubmitChanges'(without this, no changes will be reflected to database):
01/// <summary>
02/// Create A New User
03/// </summary>
04/// <returns>True=User Created Successfully/False=User Couldn't Be Created</returns>
05public static bool CreateUser(string userName, string passWord,int roleId)
06{
07            User user = new User();
08            user.Username = userName;
09            user.Password = passWord;
10            user.RoleId = roleId;
11            UserDataContext UDB = new UserDataContext();
12            UDB.Users.InsertOnSubmit(user);
13            UDB.SubmitChanges();
14}
For your information, the above code example is for .NET 3.5+ . If you are using an earlier version, you will have to use 'Add' method instead of 'InsertOnSubmit' . From .NET 3.5, the 'Add' method is removed.
If you want to insert more than one row, then you will have to create a 'List' array object containing all the 'User' objects and then use 'InsertAllOnSubmit' method, it will work fine.

Delete Data Using LinQ:

Deleting data/row from database using linq is as simple as inserting data and this is also sql syntax free operation :) . First, we will have to retrieve the 'user' object we want to delete, and then add this deletion operation in the queue by 'DeleteOnSubmit' method. Finally commit the operation using 'SubmitChanges' method as before;
01/// <summary>
02/// Delete A User
03/// </summary>
04/// <returns>True=User Deleted Successfully/False=user Couldn't Be Deleted</returns>
05public static bool DeleteUser(int userId)
06{
07    UDB= new UserDataContext();
08    User user = UDB.Users.Single(u => u.Id == userId);
09    UDB.TVUsers.DeleteOnSubmit(user);
10    UDB.SubmitChanges();
11    return true;
12}
Just like insert operation, this delete operation example given above will work for .NET framework 3.5+ and for earlier framework version, you will have to use 'Remove' method instead of 'DeleteOnSubmit' method.
For Removing More than one database records, follow the code example below:

1List<User> users = (List<User>)from u in UDB.Users
2                        where u.RoleId = 2
3                        select u;
4UDB.Users.DeleteOnSubmit(user);
5UDB.SubmitChanges();

Edit/Update Data With LinQ To SQL:

To edit data, simply first, we will have to retrieve the objects(rows) and make changes to them wherever needed. Then just use the 'SubmitChanges' method to commit the changes to database. Here is a simple code example below which will change a single row:(There is no difference between this and changing multiple row only need to retrieve multiple objects and change them)
01public static bool SaveUser(User user)
02{
03    UDB= new UserDataContext();
04    User nUser = UDB.Users.Single(u => u.Id == user.Id);
05    nUser.RoleId = user.RoleId;
06    nUser.Username = user.Username;
07    nUser.Password = user.Password;
08    UDB.SubmitChanges();
09    return true;
10}
You will notice an interesting thing here, we didn't had to use any extra method to tell DataContext object to notify the changes like 'InsertOnSubmit' or 'DeleteOnSubmit' methods before . We don't have to, because the DataContext object keeps track of all objects it is containing in a time frame(after we retrieving them). When the 'SubmitChanges' method called, it simply commits its all containing objects' changes. So, here its automatically reflecting when we made change in the 'nUSer' Object. However, the following code won't work:

1public static bool SaveUser(User user)
2{
3     UDB= new UserDataContext();
4     User nUser = UDB.Users.Single(u => u.Id == user.Id);
5     nUser = user;
6     UDB.SubmitChanges();
7      return true;
8}
This won't work because it causes the nUser object to point another memory location reference and that memory location isn't tracked by DataContext object. Thus, no changes will be reflected to your database.

Retrieve The SQL Query Text From LinQ:

Sometime, while writing comparatively big linq to sql query, you might be interested to see what kind of resultant sql query is actually generated for a specific kind of operations. This will be helpful for debugging purpose and also to learn/know more about original sql syntax. Here is a simple code snippet that will show how to get the corresponding sql query of a linq to sql operation and print it on console:
01UDB= new UserDataContext();
02//simple query
03var results =
04    from u in TV.Users
05    where u.UserName == "Admin"
06    select u;
07//database command object
08DbCommand dc = db.GetCommand(q);
09//Show the command text/sql query text on console
10Console.WriteLine("\nCommand Text: \n{0}",dc.CommandText);

Comments

Popular posts from this blog

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...

Net FrameWork (Basic Concepts)

Net FrameWork (Basic Concepts) See more presentations by aSGuest51943  |  Upload your own PowerPoint presentations .Net Framework (Basic Concepts) : .Net Framework (Basic Concepts) 1 Amrita Academy For Career Excellence Overview of the .NET Framework : Overview of the .NET Framework Software development environment which helps developers to develop applications quickly and gives optimum, efficient, scalable, performance oriented applications in different languages like Visual Basic .NET, C#, ASP.NET, and Jscript .NET etc... 2 Amrita Academy For Career Excellence Slide 3: Services NET Framework provides the following services: Tools for developing software applications , run-time environments for software application to execute, server infrastructure, value added intelligent software which helps developers to do less coding and work efficiently. The .Net Framework will enable developers to develop applications for various devices and platforms like window...

Crystal and Reporting Services Interview Questions - Part 2

Introduction   This FAQ will give you a quick start for two report giant's crystal and reporting services. We have two IIS application 'Reports' and 'Reportserver' what do they do ?   When you install reporting services there are two virtual directories created as shown in the figure below. Figure : - IIS Applications for reports The 'Reports' virtual directory is like an admin. If you browse to http://yourpcname/reports/home.aspx   page you can view, edit properties and display reports. We have numbered the below figure. 1 à We can browse reports and see the output of reports. 2 à We can upload a RDL file directly in the report's database. 3 à Using the report builder link we build new reports. 4 à Using the properties we can do role assignment. 5 à Using subscription link we can add new outputs (FTP, Folder etc) to subscribe to the reports. 6 à Site settings help us to decide how many numbers of snapshots we want in the history, report time out...