Add field annotations to the entity model EDMX file for Ef6

Source: Internet
Author: User

Code smith template (to download code Smith software use):

Generate comment Section code

<%--name:edmx file plus comment author:pukuimindescription:--%><%@ Template language= "C #" targetlanguage= "XML"%> <%@ Assembly name= "schemaexplorer"%><%@ import namespace= "schemaexplorer"%><%@ import namespace= " System.Globalization "%><%@ Import namespace=" System.Collections.Generic "%><%@ Map name=" Csharpalias " Src= "System-csharpalias" description= "database field type and C # type mapping table"%><%--Database--%><%@ property Name= "SourceDatabase "Type=" Schemaexplorer.databaseschema "deepload=" True "optional=" False "category=" required Databases "description=" database "% ><%--the table to be printed--%><%@ property name= "table" type= "Schemaexplorer.tableschema" deepload= "True" optional= " False "category=" required data table "description=" table. "%><%@ Property name=" Isall "type=" System.Boolean "optional=" false Whether "category=" generates all Tables "default=" True "description=" generates all Tables "%><%/*for (int i=tablename.length-1;i>=0;i--) {if ( tablename[i]>= ' A ' && tablename[i]<= ' Z ') {TablenamE=tablename.substring (0,i) +tablename.substring (i,1).        ToLower () +tablename.substring (i+1);    Break }}*/string Primaryname=table.primarykey.membercolumns[0]. Name;string primarytype= Csharpalias[table.primarykey.membercolumns[0]. Systemtype.fullname];string autoname= "", autotype= ""; foreach (Columnschema cs in table.columns) {if ((BOOL) CS. extendedproperties["Cs_isidentity"]. Value) = = True) {Autoname=cs.        Name; Autotype=csharpalias[cs.         Systemtype.fullname];     Break }}list<string> fkeys=new list<string> ();//Store the foreign key column and the corresponding primary key table name foreach (var item in Table.foreignkeys) {Fkeys. ADD (item. Foreignkeymembercolumns[0].    Name); Response.Write (item. Foreignkeymembercolumns[0]. Name+ "--" +item. Primarykey.table.name+ "\ n"); }tableschemacollection tables=new tableschemacollection (); if (Isall!=true) {tables. ADD (Table); }else{Tables=this. Sourcedatabase.tables; }%><%//if (tables==null) {response.writeline ("empty"); return;}//else {Response.writeliNE (Tables. Count);} %><schema><!--Manual Modify begin--> <!--copy Replace the Schema within the edmx:conceptualmodels in the edmx file, ENTITYC Ontainer the corresponding contents--<%foreach (Tableschema table in tables) {string tablename=table.            Name; %> <entitytype name= "<%=TableName%>" > <Documentation> <summa Ry><%=table. description%></summary> </Documentation> <Key> <propertyre F name= "<%=primaryname%>"/> </Key> <% for (int i=0;i<table. columns.count;i++) {Columnschema col=table.                     Columns[i]; String Lowertype=csharpalias[col.                 Systemtype.fullname]; String Type=col.                 SystemType.FullName.Replace ("System.", ""); String Nullable=col. AllowDBNull? ":" Nullable=\ "false\" ";//Can I empty string maxlength= (type==" string "?"). Maxlength=\"+col." Size+ "\" ":" ");//String unicode= maximum length (col. datatype.tostring () = = "Ansistring"? " Unicode=\ "false\" ":(Col. datatype.tostring () = = "String"? " Unicode=\ "True\" ":"), or whether the Chinese string fixedlength= "" is stored;//Whether the length is fixed if (col. nativetype== "NCHAR" | | Col. nativetype== "char") fixedlength= "fixedlength=\" true\ ""; Col. NativeType is the type else if (COL) in the database. nativetype== "nvarchar" | | Col.                 nativetype== "varchar") fixedlength= "fixedlength=\" false\ "";                 String precision= ""; if (Col. scale>0) precision= "precision=\" "+col.                 Scale+ "\" "; Col. Precision%> <property name= "<%=col. Name%> "type=" <%=type%> "<%=maxlength%><%=fixedlength%><%=unicode%><%=nullable% ><%=precision%> > <Documentation> <summary><%=col. Description%></summary> </documentatiOn> </Property> <%}%&G        T </EntityType> <%}%><!--Manual Modify End--></schema>


Generate files to

<%--Name:GenerateFiles.cstAuthor:pukuiminDescription: Generate and output a template for an XML file--%><%@ template language= "C #" Targetlanguage= "Text" inherits= "Codetemplate" encoding= "Utf-8"%><%@ Assembly name= "Schemaexplorer"%><% @ Import namespace= "schemaexplorer"%><%--Database--%><%@ Property name= "SourceDatabase" type= " Schemaexplorer.databaseschema "deepload=" True "optional=" False "category=" required Databases "description=" database "%><% --the table to be printed--%><%@ property name= "table" type= "Schemaexplorer.tableschema" deepload= "True" optional= "False" category= "Required data table" description= "table."%><%@ Property name= "Isall" type= "System.Boolean" optional= "False" Category= "whether to generate all tables" default= "True" description= "whether to generate all tables"%><%--register entity Layer Model Template--%><%@ register Name= "Edmx_ Sumary "template=" EDMX_SUMARY.CST "mergeproperties=" flase "excludeproperties=" "%><script runat=" Template "    >//Solution Output Path private string Directory = String.Empty; [Editor (typeof (System.Windows.Forms.DeSign. Foldernameeditor), typeof (System.Drawing.Design.UITypeEditor)] [Optional, notchecked] [DefaultValue ("")] Publ        IC string OutputDirectory {get {return Directory; } set {if (value. EndsWith ("\ \")) value = value. Substring (0, value.            LENGTH-1);        Directory = value;        }} public string Getsubspace (string tableName) {for (int i=tablename.length-1;i>=0;i--) {if (tablename[i]>= ' A ' && tablename[i]<= ' Z ') {tablename=tablename.sub String (0,i) +tablename.substring (i,1).                ToLower () +tablename.substring (i+1);            Break    }} return tableName; }//Generate entities entity class private void generateentityclasses () {codetemplate edmx_sumarytemplate =new Edmx_suma        Ry ();        /*////generates the underlying Basedal abstract class string basedaldirectory = OutputDirectory + "\\DAL\\BaseDAL.cs"; BasedaltemplAte. SetProperty ("NM", mynamespace);//Namespace Basedaltemplate.rendertofile (basedaldirectory,true);//File Output Debug.writel        INE (Basedaldirectory + "created successfully."); * * * response.writeline ("...... ........")            Start building ............... ");                        String edmx_sumarydirectory = OutputDirectory + "\\edmx_sumary.xml";            Generate Service file Edmx_sumarytemplate.setproperty ("SourceDatabase", sourcedatabase);            Edmx_sumarytemplate.setproperty ("table", table);            Edmx_sumarytemplate.setproperty ("Isall", Isall); Edmx_sumarytemplate.rendertofile (edmx_sumarydirectory,true);//File Output Response.writeline (edmx_sumaryDirectory + "Gen                        Success. "); Response.writeline ("....... .........")    Complete build ............... "); }</script><%//Create entity-level entities class this.    Generateentityclasses (); Debug.WriteLine ("All builds are complete!    "); Response.writeline ("All builds are complete! ");%>


C # new Console application to annotate fields in EDMX:

    Class Program {static void Main (string[] args) {work wk = new work (); Wk.            DoWork ();        Console.readkey (); }} public class work {//files are put into the generated EXE under the same directory execution  public string inxmlpath = "Edmx_sumary.xml";//code Smith generates        The comment file public string outxmlpath = "SYSENTITIES.EDMX";            public void DoWork () {String InFile = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, Inxmlpath);            String OutFile = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, Outxmlpath);            XmlDocument Inputdoc = new XmlDocument ();            XmlDocument Outputdoc = new XmlDocument ();            Inputdoc.load (InFile);            Outputdoc.load (OutFile);            XmlNodeList inlist = inputdoc.selectnodes ("/schema/entitytype");            if (inlist = = NULL | | inlist.count = = 0) return;            XmlNamespaceManager Xmlnsmanager = new XmlNamespaceManager (outputdoc.nametable); Xmlnsmanager.addNamespace ("edmx", "http://schemas.microsoft.com/ado/2009/11/edmx");            Xmlnsmanager.addnamespace ("annotation", "http://schemas.microsoft.com/ado/2009/02/edm/annotation");            Xmlnsmanager.addnamespace ("Customannotation", "http://schemas.microsoft.com/ado/2009/02/edm/customannotation"); "/edmx:edmx/edmx:runtime/edmx:conceptualmodels/edmx:schema/edmx:entitytype" XmlNode Outschemanode = OUTPU Tdoc.selectsinglenode ("/edmx:edmx/edmx:runtime/edmx:conceptualmodels", Xmlnsmanager).            Childnodes[0]; foreach (XmlNode innode in inlist)//Loop multiple table comments {if (Innode.nodetype = = xmlnodetype.comment) contin                Ue                XmlElement inelement = (XmlElement) Innode;                String tableName = Inelement.getattribute ("Name");  Console.Write (TableName + ";                ");                Console.WriteLine ();                XmlElement outelement = null; foreach (XmlNode outnodetemp in outschemanode.childnodes)//Find the Output File table node corresponding to the input File table node {if (Outnodetemp.nodetype = = Xmlnodetype.comment | | outnodetemp.n Ame = = "EntityContainer" | |                    Outnodetemp.name = = "Association") continue;                    XmlElement xe_edmx = (XmlElement) outnodetemp; String o_tablename = xe_edmx.                    GetAttribute ("Name");                    if (O_tablename = = tableName) {outelement = xe_edmx; break;                }} if (outelement = = null) continue;                Console.WriteLine ("EDMX:" + outelement.getattribute ("Name")); foreach (XmlNode field in Outelement.childnodes) {if field.                    NodeType = = xmlnodetype.comment) continue;                    XmlElement field_element = (XmlElement) field; if (field_element. NodeType = = Xmlnodetype.comment | | Field_element. Name = = "NavigationProperty" | | Field_element.        Name = = "Key") continue;            if (field_element. Name = = "Documentation") outelement.removechild (field);//delete the original table comment of the output file}//outputdoc.save (out File + "new.edmx");                Return foreach (XmlNode field in inelement.childnodes)//Loop input file each field {if (field. NodeType = = Xmlnodetype.comment | | Field.                    name== "Key") continue;                    XmlElement field_element = (XmlElement) field; String fieldName = Field_element.                    GetAttribute ("Name"); if (field_element. Name = = "Documentation") {XmlElement temp = outputdoc.createelement ("Documentat                        Ion "," Http://schemas.microsoft.com/ado/2013/11/edm/Property ");                        XmlElement TEMPC = outputdoc.createelement ("Summary"); TEMPC. InnerText = field.                        InnerText; Temp.                        AppendChild (TEMPC); Console.WriteLine ("Val:" + temp.)                        Value); OuteLement.                    AppendChild (temp); } else if (field_element.                        Name = = ' property ') {foreach (XmlNode outfield in outelement.childnodes) {if (outfield.                            NodeType = = xmlnodetype.comment) continue;                            XmlElement outfield_element = (XmlElement) outfield; if (outfield_element. GetAttribute ("Name") = = FieldName) {outfield. InnerXml = field.                            innerxml;//Modify the input file properties into the output file. }}}}} outputdoc.save (OutFile + "new.edm        X "), or//save to a new file, or save to the original file, it is best to back up the original file. }    }




The TT template also writes the code to read the comment from the EDMX, and now the comment is already in the edmx file, which can be opened for viewing in Notepad.

About TT read the comments in the EDMX, the online code is many, is feasible.






Add field annotations to the entity model EDMX file for Ef6

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.