LINQ-to-MySQL with DbLinq in C# - Let's Do It!
(Page 3 of 4 )
First of all you should do the basic groundwork of the application. That is, design its forms if you are not creating a console application. This article focuses strictly on the database part-where we are using DbLinq Provider and the LINQ native querying.
You can connect to the database in the following fashion:
hotels.HotelsDb db = new hotels.HotelsDb(new MySqlConnection("Database=hotelsdb;Data Source=localhost;User Id=root;Password=rootpassword"));
As you can see in the code snippet above, the namespace in my case is hotels, while hotelsdb is the name of the database. We're going to use db as the handler after the connection is established. Don't forget to write the correct server details.
Natively querying entries from the Hotels table can be done in the following way. This solution iterates through the hotels collection and writes the name of each hotel to a textbox (Name is a string attribute of the Hotel table). Should you want to create a more advanced view of results, you should plan on doing it with DataGridView.
var hotels = from h in db.Hotels select h;
foreach (var hotel in hotels){
txtBox1.Text += hotel.Name + "rn";
}
Now we want to exemplify the insert operation also. We have the following form.

And by using the following code snippet we are inserting the newly-created client in the appropriate Client table. First, we will count the total number of clients that are to be found in the table. This is important because we want to add +1 to this value; it is going to stand for the IDClient (primary key). Then insert each string appropriately.
var countClients = (from c in db.Clients
select c).Count();
int newID = countClients + 1;
db.Clients.InsertOnSubmit(new hotels.Clients{
IDClient = newID,
Name = txtName.Text.ToString(),
Address = txtAddress.Text.ToString(),
Phone = txtPhone.Text.ToString(),
Zip = txtZIP.Text.ToString()
});
db.SubmitChanges();
Deleting an entry from the table can be accomplished quite easily. We want to ask the user for the name of the Client, and then we can execute the delete operation. First we want to locate where that deleteable (the row which is going to be deleted) exists, and then we delete it. Check out the form below together with the code snippet.

hotels.Clients deleteable =
(from c in db.Clients
where c.Name == txtClient.Text.ToString()
select c).First();
db.Clients.DeleteOnSubmit(deleteable);
These basic actions should suffice as an example of how to work with DbLinq.
Next: Final Thoughts >>
More C# Articles
More By Barzan "Tony" Antal