LINQ to SQL Tips 8: How to (and why) create a partial class in the designer to augment generated code
The code generated for LINQ to SQL is a set of partial classes - one for your DataContext and one per entity mapped to a table or a view. That means you have the opportunity to augment the generated code with additional code in your partial class. I often get questions that have a simple answer in the following list. The code you write could be for:
- Adding unmapped fields or properties to an entity class (e.g. computed property - amount for an Order class based on price, quantity, freight, taxes etc.)
- Providing an implementation of a validation method defined as a partial method (e.g. for a mapper property called "Name", OnNameChanging(), OnNameChanged() or for an entity OnValidate() etc)
- Providing an implementation of CUD override methods supported by the DataContext (e.g. InsertOrder, UpdateOrder, DeleteOrder). You may choose to call a method wrapping a CUD sproc in the method body and/or do more customization.
- Providing an implementation of relationship load override method (e.g. LoadOrders(Customer cust), LoadCustomer(Order ord) etc.). Again, you may choose to call a method wrapping a query sproc in the method body and/or do more customization.
- Add a method to call a sproc returning multiple results (see this previous post for more details)
- Adding utility methods to entity classes or your DataContext class
That sounds like a good bunch of reasons. But I often get a followup question - is there an easy way to do this in the designer? Of course, you can add a new class to a project anytime but a somewhat stylized way is to right click on the design surface and click "View code" (don't ask me why that name was chosen for creating a new partial class). If I do that for Northwind.dbml (file opened in the designer), I get a Northwind.cs at a peer to Northwind.designer.cs.
The file already contains a little class wrapper. It is not a big deal to add that by hand using code snippets but it is another little bit we could do for you (and did in this case).
June 16 addendum: Steve has rightly pointed out that the behavior is different in website projects. My colleague Young Joo - PM for the designer explained the rational as follows "We disabled View Code in website project since it actually has a different meaning than other project types. The View Code option from Dataset Designer within Windows Application project, for instance, creates the partial class file. However, it opens .XSD file in the editor in website project."
So in website project, you will need to resort to the good old way of adding a class through the solution explorer. Thanks Steve!