Adding Business Logic By Using Partial Methods
You can customize Visual Basic and C# generated code in your LINQ to SQL projects by using partial methods. The code that LINQ to SQL generates defines signatures as one part of a partial method. If you want to implement the method, you can add your own partial method. If you do not add your own implementation, the compiler discards the partial methods signature and calls the default methods in LINQ to SQL.
If you are using Visual Studio, you can use the Object Relational Designer to add validation and other customizations to entity classes. How to: Add Validation to Entity Classes
For example, the default mapping for the Customer class in the Northwind sample database includes the following partial method:
You can implement your own method by adding code such as the following to your own partial Customer class:
This approach is typically used in LINQ to SQL to override default methods for Insert, Update, Delete, and to validate properties during object life-cycle events.
' Code-generating tool defines a partial class, including ' two partial methods. Partial Class ExampleClass Partial Private Sub OnFindingMaxOutput() End Sub Partial Private Sub OnFindingMinOutput() End Sub Sub ExportResults() OnFindingMaxOutput() OnFindingMinOutput() End Sub End Class ' Developer implements one of the partial methods. Compiler ' discards the other method. Class ExampleClass Private Sub OnFindingMaxOutput() Console.WriteLine("Maximum has been found.") End Sub End Class
Public Shared LoadOrdersCalled As Integer = 0 Private Function LoadOrders(ByVal shipper As Shipper) As _ IEnumerable(Of Order) LoadOrdersCalled += 1 Return Me.Orders.Where(Function(o) o.ShipVia = _ shipper.ShipperID) End Function Public Shared LoadShipperCalled As Integer = 0 Private Function LoadShipper(ByVal order As Order) As Shipper LoadShipperCalled += 1 Return Me.Shippers.Single(Function(s) s.ShipperID = _ order.ShipVia) End Function Public Shared InsertShipperCalled As Integer = 0 Private Sub InsertShipper(ByVal instance As Shipper) InsertShipperCalled += 1 ' Call a Web service to perform an insert operation. InsertShipperService(shpr:=Nothing) End Sub Public Shared UpdateShipperCalled As Integer = 0 Private Sub UpdateShipper(ByVal original As Shipper, ByVal current _ As Shipper) UpdateShipperCalled += 1 ' Call a Web service to update shipper. InsertShipperService(shpr:=Nothing) End Sub Public Shared DeleteShipperCalled As Boolean Private Sub DeleteShipper(ByVal instance As Shipper) DeleteShipperCalled = True End Sub