LINQ tutorial Part -II

4. Save , Update, Delete by LINQ :-  (Attached document :- linq-images )

 

 

Hello friends first of all happy new year to all of you. Today we will work on how to Save ,Update & delete record from database using linq.

For using this you have to work on Linq To sql class Object which you can find when you add new item . Its extension is “DBML”.

When you create object of this then it will add datacontext in end.

Suppose you given name mydb.dbml then its object will be “mydbDataContext”.

You will be find this in attach document (Pic -1). Its basically a ORM (object Relational mapper) just drop the table from database. You will find the relation structure as like in (pic -2) in document.

The drop table is now work as individual class and & the fields of the table work as property of class.

Suppose if you drop table Customer then it will work as customer class and fields are work as property of customer class.

Now suppose you want to add new customer in customer table in database.

Then you have to create a object of customer class like below

Dim dc as new MyDbDataContext (its object of your added dbml)

Dim obj as new customer

Obj.strFirstName = “RAJAT”

Obj.strLastName = “JAISWAL”

Dc.customer.InsertOnSubmit(obj)

Dc.submitOnChanges()

The above code add the data in database.

Now suppose you want to edit the same record from database then you have to write following code

Dim dc as new myDbDataContext

Dim lnq = (from a in dc.customer where lngId = 1).singleOrDefault()

Lnq.strFirstName =”RAJAT”

Lnq.strLastName =”JAI”

Dc.submitChanges()

In that way you can update the customer record.

Now suppouse you want to delete record from database. Then you have to write following code.

Dim dc as new mydbDataContext()

Dim lnq = (from a in dc.customer where lngId = 1) .singleOrDefault()

Dc.customer.DeleteOnSubmit(lnq)

Dc.submitChanges()

In this way we can add edit, delete record.

In next topic we will how to add,edit,delete done by store procedure.

Enjoy Programming

Regards

Rajat

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s