Research on T4 templates-Ef code generation for SQL Server

Source: Internet
Author: User

We often spend a lot of time writing entity classes, data entity classes, and business classes when doing small websites. After these things are done, we can only engage in the UI and specific services. It is a bit oily. Although there are some generation tools that can be generated, we still need to spend some effort to modify and adapt to the project, so in this study the T4 template (http://www.cnblogs.com/heyuquan/archive/2012/07/26/2610959.html), and a simple rough tool.

For SQL, generate efCodeTo generate:

Entity class: model, ing for database tables only

Data Category: currently only the EF Method

Business class: After being generated, basic new, deleted, and queried functions can be completed.

All of these codes are greasy. If you don't talk much about them, let's look at the code first and look at the ideas from the code. The following is part of the code of the tool:

1. entity class

 
Using system; using system. Collections. Generic; using system. componentmodel. dataannotations; namespace model {[Table ("accountbook")] public class accountbook: basemodelguid {public Int? Accountcode {Get; set;} public datetime? Createtime {Get; set;} public Int? Creater {Get; set;} Public String remark {Get; set;} public bool? Isdelete {Get; Set ;}}}

The generated entity classes look like this. You will notice that all object classes are derived from the basemodelguid class. In fact, this is a constraint that restricts your database design, the database table must have a primary key field named ID, nvarchar (36), which is actually used to save the guid. Why? Wait until the business class is generated. Let's take a look at the code of the base class:

 
Public class basemodel <t> {[Key] public t ID {Get; Set ;}} public class basemodelguid: basemodel <string> {public basemodelguid () {id = system. guid. newguid (). tostring ();}}

Here it means that the primary keys of the object classes corresponding to each table are placed in the base class, and the Code for generating the object class is also very simple. Let's look at the template:

<# @ Template Language = "C #" #> <# @ Assembly name = "system. core. DLL "#> <# @ Assembly name =" system. componentmodel. dataannotations. DLL "#> <# @ Assembly name =" F: \ project \ efpococscreater. usemodel \ bin \ debug \ efpococscreater. usemodel. DLL "#>< # @ import namespace =" system "#>< # @ import namespace =" system. componentmodel. dataannotations "#>< # @ import namespace =" system. collections. generic "#> <# @ Import namespace = "efpococscreater. usemodel "#> <# @ parameter name =" tempmodel "type =" efpococscreater. usemodel. creatermodel "#> using system; using system. collections. generic; using system. componentmodel. dataannotations; namespace model {[Table ("<# = tempmodel = NULL? "": Tempmodel. tablename #> ")] public class <# = tempmodel = NULL? "A": tempmodel. tablename #>: basemodelguid {<# If (tempmodel! = NULL & tempmodel. Fields! = NULL) {foreach (VAR item in tempmodel. fields) {#> Public <# = item. csdatatype #> <# = item. name #>{ get; Set ;}<#}#> }}

 

2. Data Category

First look at the generated code:

Public class basedataaccess: dbcontext {public basedataaccess (): Base ("databaseurl") {setinitializer ();} /// <summary> /// initialize the dbcontext of EF /// </Summary> protected virtual void setinitializer () {// database. setinitializer <dprojectfileinfo> (null) ;}} public class dataaccess: basedataaccess {protected override void setinitializer () {database. setinitializer <dataaccess> (null);} public dbset <accountbook> accountbook {Get; set;} public dbset <accountincome> accountincome {Get; set ;} public dbset <accountinfo> accountinfo {Get; set;} public dbset <accounttype> accounttype {Get; set;} public dbset <accountusetype> accountusetype {Get; set ;} public dbset <tbuser> tbuser {Get; set;} public dbset <v_accountbook> v_accountbook {Get; set;} public dbset <v_accountinfo> v_accountinfo {Get; set ;}}

there is nothing to say about this one. Here, EF is generating table ing in a lazy way. The generated template is also simple:

<# @ Template Language = "C #" #> <# @ Assembly name = "system. core. DLL "#> <# @ Assembly name =" system. data. entity. DLL "#> <# @ Assembly name =" F: \ project \ efpococscreater. usemodel \ bin \ debug \ efpococscreater. usemodel. DLL "#>< # @ import namespace =" system "#>< # @ import namespace =" system. data. entity "#> <# @ import namespace =" efpococscreater. usemodel "#> <# @ parameter name =" tempmodel "type =" Ef Pococscreater. usemodel. createrdataaccess "#> using system; using system. data. entity; namespace dataaccess {public class dataaccess: basedataaccess {protected override void setinitializer () {database. setinitializer <dataaccess> (null) ;}< # If (tempmodel! = NULL & tempmodel. tablesname! = NULL) {foreach (VAR item in tempmodel. tablesname) {#> public dbset <# = item #>>< # = item #>{ get; Set ;}< #}#> }}

3. Business

The business class is generated for each table object, but the initial code is few:

 
Using system; using system. collections. generic; using system. LINQ; namespace business {public class baccountbook: basebusinessstring <accountbook> {public baccountbook (): Base (New dataaccess ()){}}}

The basic addition, deletion, and query functions of the initial generation can be completed in the base class. The base class uses the generic type and restricts the derived class, therefore, the base class also integrates the deletion and search operations based on the ID. The following is a part of the base class code:

Public class basebusinessstring <t>: basebusiness <t, string> where T: basemodel <string> {public basebusinessstring (dbcontext context): Base (context) {}/// <summary> /// query by primary key /// </Summary> /// <Param name = "ID"> primary key ID </param> // /<returns> </returns> Public t findbyid (string ID) {return findbypredicate (P => P. id = ID );} /// <summary> /// Delete by ID /// </Summary> /// <Param name = "ID"> </param> protected virtual void pdeletebyid (string ID) {pdeletebymodel (findbyid (ID ));} /// <summary> /// Delete by ID /// </Summary> /// <Param name = "ID"> </param> Public Virtual bool deletebyid (string ID) {pdeletebymodel (findbyid (ID); Return context. savechanges ()> 0 ;}}

In this way, the entity class, data access, and basic business class that can cope with small website projects will be generated, and the rest of the time will be directed to the specific business and UI.

Finally, the tool is very rough, simple, and targeted (basically generated for the code in the cstemp directory.

In total, only the T4 template is used to read the database and encapsulate some basic classes.

InProgramDirectory:

CS code: directory of the generated code

Cstemp: The base class code that the generated code depends on.

DLL: The DLL file on which the generated code depends

Temp: T4 template file directory

 

The next step is to upload the Source Code. The Code is ugly and you can watch it carefully. I also hope you can point out the following defects.

Code

 

 

Related Article

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.