Introduction to the MVC T4 template

Source: Internet
Author: User

Personal website Address: nee32.com

First, T4 template content Introduction

To better learn the T4 template, we install a plugin tangible T4 Editor after using EF to generate the entity classes, we will find a. tt suffix file, which is the T4 template that directly opens its contents such as:

This is the template that generates the classes we need, eliminates the hassle of our handwriting, improves productivity, and generates entity classes such as:

So, how are these classes generated using T4 templates? What do I do to customize a template?

The following is a brief introduction to the core code in the T4 template

1. Global variable Declaration

<#@ template language= "C #" debug= "false" hostspecific= "true" #>//template instruction set tells the editor that this is a template in the C # language, <#@ include file= "EF. Utility.CS.ttinclude "#>  //Import external template <#@ output extension=". cs "#>//  output file with. cs extension

The above code defines the global variables to be used (such as the edmx file to map the class, the reference namespace, the entity class collection, and so on ...). )

2. Generate class top comment, entity class namespace, and entity class name and suffix name

Writeheader (Codestringgenerator, FileManager);//generate the topmost comment in the class foreach (var entity in typemapper.getitemstogenerate< Entitytype> (ItemCollection)) {    Filemanager.startnewfile (entity. Name + ". cs");//Generate class name and Add. cs suffix name    beginnamespace (code);//Generate Class namespace    ...}

This code generates the corresponding class file as

3, the reference space name Usingdirectives method

public string usingdirectives (bool Inheader, bool includecollections = True)    {        return inheader = = string. IsNullOrEmpty (_code. Vsnamespacesuggestion ())            ? string. Format (                cultureinfo.invariantculture,                "{0}using system;{ 1} "+                " {2} ",                Inheader? Environment.NewLine: "",                includecollections? (Environment.NewLine + "using System.Collections.Generic;") : "",                inheader? ": Environment.NewLine)            :" ";    }

The system and System.Collections.Generic are referenced by default, such as:

4. Define the class name Entityclassopening method

public string entityclassopening (EntityType entity)    {        return string. Format (            cultureinfo.invariantculture,            "{0} {1}partial class {2}{3}",            Accessibility.fortype (entity),            _code. SpaceAfter (_code. Abstractoption (entity)),            _code. Escape (entity),            _code. Stringbefore (":", _typemapper.gettypename (entity. BaseType)));    }

Accessibility.fortype (entity) access modifier, _code. Escape (Entity) class name, such as:

5. Generate Field Properties Property method

public string Property (Edmproperty Edmproperty)    {        return string. Format (            cultureinfo.invariantculture,            "{0} {1} {2} {{{3}get}}; {4}set; }} ",            Accessibility.forproperty (edmproperty),            _typemapper.gettypename (edmproperty.typeusage),            _code . Escape (Edmproperty),            _code. SpaceAfter (Accessibility.forgetter (Edmproperty)),            _code. SpaceAfter (Accessibility.forsetter (Edmproperty)));    }

Accessibility.forproperty (edmproperty) access modifier, _typemapper.gettypename (edmproperty.typeusage) field data type, such as:

Ii. T4 Template extension inherit base class, interface

In general, we define some common methods in the base class that allow subclasses to inherit directly, defining the following base classes:

public class ientity<t> where T:class, new ()    {        Private DbContext db        {            get            {                return EFDBC Ontextfactory.getcurrentdbcontext ();            }        }        <summary>/////</summary>//        <param name= "where" ></param>        ///<returns></returns> public T Find (expression<func<t, bool>> where = null)        {            if (where = = null)                return DB. Set<t> (). FirstOrDefault ();            else                return DB. Set<t> (). where (where). FirstOrDefault ();        }    }

Directly modify the definition class name Entityclassopening method in the T4 template, inherit the base class Find method, the modified code is as follows:

public string entityclassopening (EntityType entity)    {        return string. Format (            cultureinfo.invariantculture,            "{0} {1}partial class {2}{3}: ientity<{2}>",            Accessibility.fortype (entity),            _code. SpaceAfter (_code. Abstractoption (entity)),            _code. Escape (entity),            _code. Stringbefore (":", _typemapper.gettypename (entity. BaseType)));    }

Then just save it and look at the classes generated by the T4 template, and discover that they all automatically inherit the IEntity class, such as

Called, directly b_article model = new B_article (). Find (c = c.username = = "Tess");

Introduction to the MVC T4 template

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.