Friday, July 3, 2009

Linq to Sql example

linq to sql
Still a bit fuzzy.


In Databse explorer, add an MDF type file. O/R mapping only works with MDF files, not SDF or MDB files.




pROJECT > aDD cLASS > Linq to Sql
If your database is Foo, it is best to label it as Foo, thereby creating Foo.dbml.
You have created a customer object. It opens up the O/R designer. Take a note of the Name property. It'll be something like $BazDataContext


Drag the relevant table from the Database Explorer to the O/R designer. that creates a table object. It automatically created a LinqToSql class for you.


Press save.

Go to Data Sources tab (on right).
Add new data source
Choose a Data Source Type: Object
Expand your application name until you find the relevant object
This will create a data source in the Data Source window.


Go to a form.

From the data sources panel, drag the dataset you are interested in onto the form.




Enable save:
Click the save button
Enabled: True
double-click it. Enter code for
PeopleBindingNavigatorSaveItem_Click


You can add a search button and obtain code like this:
Public Class Form2

Private Db As New BazDataContext()

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Db.Log = Console.Out
MySubitems()


End Sub

Private Sub MySubitems()
Dim qryString = "*" & txtSearch.Text & "*"

Dim recs = From rec In Db.Peoples _
Where rec.name Like qryString _
Order By rec.name _
Select rec
Me.PeopleBindingSource.DataSource = recs
End Sub
Private Sub PeopleBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PeopleBindingNavigatorSaveItem.Click
Me.Validate()
Me.PeopleBindingSource.EndEdit()

Try
Db.SubmitChanges()
MsgBox("Saved changes")
Catch ex As Exception
MsgBox(ex.ToString)
End Try

End Sub

Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
MySubitems()
End Sub

Private Sub txtSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.Click

End Sub
End Class




Created: 04-Jun-2009

No comments: