Code first uses the T4 template

Source: Internet
Author: User

Http://stackoverflow.com/questions/23347093/dbcontext-generator-t4-templates-with-code-first

Dbfist using the T4 template edmx file

Codefirst does not have an edmx file, only the DbContext class file, a little bit different.

First step, add EF6.Utility.CS.ttinclude file

Path to C:\Program Files (x86) \microsoft Visual Studio 12.0\common7\ide\extensions\microsoft\entity Framework tools\ Templates\includes


Step two, modify this file

There are three methods in the include file that are important

 Public Ienumerable<globalitem> createedmitemcollection (string  sourcepath) Public XElement loadrootelement (string  sourcepath)privatevoidstring Sourcefilepath)

The most important is the Loadrootelement method, which reads the XML file, because Codefirst does not have an edmx and no such XML file, we prepare a memory stream to access the DbContext information.

Add two methods to the inside of the

 PublicIenumerable<globalitem>createedmitemcollection (DbContext DbContext) {argumentnotnull (DbContext,"DbContext"); varSchemaelement =loadrootelement (DbContext); if(Schemaelement! =NULL)    {        using(varReader =Schemaelement.createreader ()) {IList<EdmSchemaError>errors; varItemCollection = Edmitemcollection.create (New[] {reader},NULL, outerrors);            Processerrors (errors, dbContext.Database.Connection.ConnectionString); returnItemCollection??Newedmitemcollection (); }    }    return Newedmitemcollection ();} PublicXElement loadrootelement (DbContext DbContext) {argumentnotnull (DbContext,"DbContext");    XElement Root; using(varstream =NewMemoryStream ()) {        using(varwriter =XmlWriter.Create (Stream))        {EDMXWRITER.WRITEEDMX (dbContext, writer); } stream. Position=0; Root= Xelement.load (Stream, Loadoptions.setbaseuri |loadoptions.setlineinfo); Root=Root. Elements (). Where (e= = E.name.localname = ="Runtime")            . Elements (). Where (e= = E.name.localname = ="Conceptualmodels")            . Elements (). Where (e= = E.name.localname = ="Schema")            . FirstOrDefault ()??Root; }    returnRoot;}

Then import the namespaces

<name= "System.Data.Entity"  #><   namespace= "System.Data.Entity"  #><   namespace= "System.Data.Entity.Infrastructure"  #>

Step three, modify the T4 file

To generate multiple CS files:

<#@ Templatelanguage= "C #"Debug= "false"hostspecific= "true"#><#@ Assemblyname= "$ (solutiondir) Web\bin\model.dll"#><#@ includefile= "EF6." Utility.CS.ttinclude "#><#@ Outputextension= ". txt"encoding= "Utf-8"#><#//Template Preparation Conststring connectionString= @ "server= (LocalDb) \v11.0;database=db;integratedSecurity=true; Multipleactiveresultsets=true ";var texttransform= Dynamictexttransformation.create (this);var code= newCodegenerationtools (this); var ef= newMetadatatools (this); var typemapper= newtypemapper (Code, EF, texttransform.errors); var filemanager= Entityframeworktemplatefilemanager.create (this);Ienumerable<globalitem>itemcollection;using (var dbContext = new Model.codefirstcontext (connectionString)) {itemcollection = new Edmmetad Ataloader (Texttransform.host, texttransform.errors).    Createedmitemcollection (DbContext); if (itemcollection = = null) {return string.    Empty; }}var codestringgenerator = new Codestringgenerator (code, typemapper, EF); Typemapper.verifycaseinsensitivetypeuniqueness (Typemapper.getallglobalitems (itemcollection), connectionString)) {return string. Empty;} Writeheader (Codestringgenerator, FileManager); foreach (var entity in Typemapper.getitemstogenerate<EntityType>(ItemCollection)) {Filemanager.startnewfile ("I" +entity. Name + "BLL.cs");#>
Model.dll is a class library that contains dbcontext files.
Next comes your own code
foreach (var entity in Typemapper.getitemstogenerate<EntityType>(ItemCollection)) {Filemanager.startnewfile ("I" +entity. Name + "BLL.cs");#><# Beginnamespace(code);><#=codestringgenerator.usingdirectives(inheader:false) #><#= " publicinterface I "+entity. Name+ "BLL:IBASEBLL" #>{}<# Endnamespace(code);><# }#>

To generate a single CS file:

using system;using system.collections.generic;using system.linq;using system.text;namespace IBLL{public Partial Interface ibllsession{<# foreach(var entity in Typemapper.getitemstogenerate<entitytype>(ItemCollection)) {#> I<#=entity. Name#>BLL I<#= entity. Name#>BLL {get;set;}<#}#>}}

Here are some of the methods in the template, do not change.

Add: How does the method in the template come from.

Create a new ADO data file, connect to the database will get the edmx file, there is, you can copy.

This is Ef6 's TT template, and we're just going to change the template header file to read the assembly instead of the edmx file.

Code first uses the 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.