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

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