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

WPF Tutorials - Binding Validation Rules

Bindings are a major part of WPF, and a big part of what makes it quick to create user interfaces in. They can be a little wordy and hard to debug sometimes, but overall they are extremely useful. Hopefully, after today's tutorial, you will find them even more useful - because today we are going to talk about building validation rules right into your bindings. Yup, you heard right - bindings in WPF have built in support for validation, and a number of the common controls have built in ways for displaying validation errors. Today we are going to build a simple little WPF application that has a TextBox in which the user is supposed to enter an IP Address (a v4 address - I was lazy and didn't want to write a validator for ipv6 as well :P). Below you can see a screenshot of the the app in action: A valid IPv4 address An invalid IPv4 address So the first thing that we need to do to add validation to a binding is to create a validation ru...

WPF Tutorial - Command Bindings and Custom Commands

Well, today we are going to take a look at the other side of that - creating and using your own custom command and command bindings. First we will take a look at setting up our own bindings to existing commands, and then we will see how to create our own commands from scratch. So an important thing to know, in order for command binding to make sense, is that (like many things in WPF) commands bubble. So when a command is triggered, it bubbles up along the WPF element tree from its origin (the command target, which we talked about in the previous tutorial), looking for an element that recognizes and can handle the command. The way that you can set up an element to handle a command is by creating a command binding. This can be done in either XAML or the code behind code - and we are going to take a look at the XAML first. <Window x:Class = "CustomCommandTest.CommandWindow"     xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"     ...

WPF Tutorial - Using The Built-In Commands

One of the features that WPF has is actually a blast from the past - something that MFC used to have, but was never included in WinForms. This is the concept of Commands. Commands are somewhat like events in that they are based on actions in the user interface, a command can get triggered (just like an event). But unlike regular events like 'click', commands are built in a way that makes it very easy to expose the same functionality at multiple places in an interface, with very little code duplication. On of the very useful features of commands is the fact that you actually get an automatic form of two way communication between the interface elements and the command they are bound too. This is because a command is made up of two main elements - Execute and CanExecute . So unlike in the regular world of events, when an action becomes unavailable, you can just have the CanExecute part of the command return false - and everything hooked to that command becomes d...