How to: Extend code generated by the O/R Designer

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Code generated by the O/R Designer is regenerated when changes are made to the entity classes and other objects on the designer surface. Because of this code regeneration, any code that you add to the generated code is typically overwritten when the designer regenerates code. The O/R Designer provides the ability to generate partial class files in which you can add code that is not overwritten. One example of adding your own code to the code generated by the O/R Designer is adding data validation to LINQ to SQL (entity) classes. For more information, see How to: Add validation to entity classes.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in this article. You may be using a different edition of Visual Studio or different environment settings. For more information, see Personalize the IDE.

Add code to an entity class

To create a partial class and add code to an entity class

  1. Open or create a new LINQ to SQL Classes file (.dbml file) in the O/R Designer. (Double-click the .dbml file in Solution Explorer or Database Explorer.)

  2. In the O/R Designer, right-click the class for which you want to add validation and then click View Code.

    The Code Editor opens with a partial class for the selected entity class.

  3. Add your code in the partial class declaration for the entity class.

Add code to a DataContext

To create a partial class and add code to a DataContext

  1. Open or create a new LINQ to SQL Classes file (.dbml file) in the O/R Designer. (Double-click the .dbml file in Solution Explorer or Database Explorer.)

  2. In the O/R Designer, right-click an empty area on the designer and then click View Code.

    The Code Editor opens with a partial class for the DataContext.

  3. Add your code in the partial class declaration for the DataContext.

See also