Adding a T4 template

Before we look at the Entity Framework-specific aspects of T4 templates, let’s get our feet wet with a simple example. We’ll start by adding a new template to the project:

Image

Add a new project item by choosing Add New Item from the Project menu or the Project context menu. Choose Text Template from the Add Item dialog:

Image
Image

Once you’ve named your template, click Add and Visual Studio will add the template and its (currently empty) output file to the Solution, and open the template in an editor window.

Image

Image Put On Your Thinking Hat

Once you’ve added the text template to your project, Visual Studio will open it in a text editor tab. A template and an output directive will already have been added for you. Referring to the syntax diagrams on pages 178 and 179, can you buld a template to output the following text?

Image


Image Make A Note

Visual Studio doesn’t provide direct support for editing T4 templates. By default, you’ll get a text editor without Intellisense or any of the other IDE goodies we’ve grown to love and hate. Several third-party T4 editors are available, however. Search for “T4 editor” in  the Visual Studio Extension Manager (available from the Tools menu) or in your favorite search engine.



Image Put On Your Thinking Hat

How’d you do? Don’t worry if your function doesn’t look like mine. As long as it returns the correct result, you’re fine.

Image
Image
Image
Image

Image Take a Break

Text templates can be complex, but the principles are (as I hope you’ve seen) pretty straightforward. If you decide you need this functionality, there are lots of resources and samples on the Web, but for now, why don’t you take a break before you complete the Review and we move on to the final way of creating a model, Code First, in the next chapter?



..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset