Friday, October 07, 2005

Insert and Delete with DLinq

In my last entry, I showed how to fetched record from SQL server using LINQ. I did some more work on LINQ and was able to insert a new record and delete particular record using LINQ. In order to insert or delete, I needed to start Distributed Transaction Coordinator in my SQL server. Below is the simple code use to insert a record,
Authors aut = new Authors();

aut.AuId = id;
aut.AuFname = fName;
aut.AuLname = lName;
aut.Phone = phone;

Continuing the work I left last time, I made an object of Authors and added ID, first name, last name and phone to it. Then calling the SubmitChanges method, the actual data is written to database. Similarly, deleting a record is also not so hard.
var authors = (
    from a in db.Authors
    where a.AuId == id
    orderby a.AuFname
    select a).First();


In order to delete a record, First method is called with the query, which returns a particular record. By passing this record to the Remove method of Authors object, a record will be deleted. With this, record deletion is only limited to memory data. Actual record will be deleted only after calling SubmitChanges method. The next step is to explore transaction in LINQ.

1 comment:

This Just In said...

Very helpful, thanks!!!