Database operations using Silverlight 2.0 WCF and LINQ to SQL - Developing a WCF Service to interact with LINQ to SQL for all CRUD operations
(Page 2 of 5 )
Let us start with a new solution:
Create a new Visual Studio 2008 solution.
Add a new WCF Service project named “DemoEmpService.”
Modify all “Service1” to “EmpService” everywhere in the project (steps are shown in my previous articles).
Add a “LINQ to SQL Classes” item to the project (“DemoEmp.dbml”)
Using “Server Explorer,” drag and drop “Emp” and “Dept” tables as shown in the following image.

<ServiceContract()> _
Public Interface IEmpService
<OperationContract()> _
Function GetEmployee(ByVal empno As Integer) As Emp
<OperationContract()> _
Function GetEmployeeList() As List(Of Emp)
<OperationContract()> _
Sub Add(ByVal objEmp As Emp)
<OperationContract()> _
Sub Update(ByVal objEmp As Emp)
<OperationContract()> _
Sub Delete(ByVal empno As Integer)
End Interface
Imports System.Data.Linq
Public Class EmpService
Implements IEmpService
Public Sub New()
End Sub
Public Function GetEmployeeList() As System.Collections.Generic.List(Of Emp) Implements IEmpService.GetEmployeeList
Using ctxt As New DemoEmpDataContext
ctxt.ObjectTrackingEnabled = False
Return ctxt.Emps.ToList
End Using
End Function
Public Sub Add(ByVal objEmp As Emp) Implements IEmpService.Add
Using ctxt As New DemoEmpDataContext
'adding a new row
ctxt.GetTable(Of Emp).InsertOnSubmit(objEmp)
'saving rows added
ctxt.SubmitChanges()
End Using
End Sub
Public Sub Delete(ByVal empno As Integer) Implements IEmpService.Delete
Using ctxt As New DemoEmpDataContext
Dim objEmpOld As Emp = ctxt.GetTable(Of Emp).SingleOrDefault(Function(p) p.Empno = empno)
If objEmpOld IsNot Nothing Then
'delete row
ctxt.GetTable(Of Emp).DeleteOnSubmit(objEmpOld)
'save changes
ctxt.SubmitChanges()
End If
End Using
End Sub
Public Function GetEmployee(ByVal empno As Integer) As Emp Implements IEmpService.GetEmployee
Dim objEmp As Emp = Nothing
Using ctxt As New DemoEmpDataContext
'retrieve emp row
objEmp = ctxt.GetTable(Of Emp).SingleOrDefault(Function(p) p.Empno = empno)
End Using
Return objEmp
End Function
Public Sub Update(ByVal objEmp As Emp) Implements IEmpService.Update
Using ctxt As New DemoEmpDataContext
Dim objEmpOld As Emp = ctxt.GetTable(Of Emp).SingleOrDefault(Function(p) p.Empno = objEmp.Empno)
If objEmpOld IsNot Nothing Then
'modify row
objEmpOld.Ename = objEmp.Ename
objEmpOld.Sal = objEmp.Sal
objEmpOld.Deptno = objEmp.Deptno
'save changes
ctxt.SubmitChanges()
End If
End Using
End Sub
End Class
Next: Developing a Silverlight 2.0 page to demonstrate CRUD functionality >>
More Windows Scripting Articles
More By Jagadish Chaterjee