26
2014
12

给ef6的实体模型 edmx文件加字段注释

code smith 模版(要下载code smith软件使用):

//生成注释部分代码

<%-- 
Name:edmx文件加注释
Author: pukuimin
Description: 
--%>
<%@ 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="数据库字段类型与C#类型的映射表" %>
<%-- 数据库 --%>
<%@ Property Name="SourceDatabase"  Type="SchemaExplorer.DatabaseSchema" DeepLoad="True" Optional="False" Category="需要的数据库" Description="Database"%>
<%-- 要打印的表 --%>
<%@ Property Name="Table"  Type="SchemaExplorer.TableSchema" DeepLoad="True" Optional="False" Category="需要的数据表" Description="table ." %>
<%@ Property Name="IsAll"  Type="System.Boolean" Optional="False" Category="是否生成全部表" Default="True" Description="是否生成全部表" %>
<% 
/*
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>();//存储外键列及对应的主键表名
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("空");return;} 
//else {Response.WriteLine(tables.Count);} 
%>
<Schema>
<!--manual modify begin-->
        <!-- 复制替换 edmx文件中的 edmx:ConceptualModels 下的 Schema 内、EntityContainer前对应的内容 -->
        <%foreach(TableSchema table in tables){
            string TableName=table.Name;
            %>
        <EntityType Name="<%=TableName%>">
             <Documentation>
                    <Summary><%=table.Description%></Summary>
             </Documentation>
             <Key>
                 <PropertyRef 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\"";//是否可空
                 string maxlength=(type=="String"?" MaxLength=\""+col.Size+"\"":"");//字符串最大长度
                 string unicode=(col.DataType.ToString()=="AnsiString"?" Unicode=\"false\"":(col.DataType.ToString()=="String"?" Unicode=\"true\"":""));//是否可存储中文
                 string fixedlength="";//长度是否固定
                 if(col.NativeType=="nchar" || col.NativeType=="char") fixedlength=" FixedLength=\"true\""; //col.NativeType为数据库中的类型
                 else if(col.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>
                        <%
                        }
                        %>
        </EntityType>
        <%}%>
<!--manual modify end-->
</Schema>


//生成文件到硬盘上

<%-- 
Name:GenerateFiles.cst
Author: pukuimin
Description: 生成并输出xml文件的模版
--%>
<%@ Template Language="C#" TargetLanguage="Text" Inherits="CodeTemplate" Encoding="utf-8"%>
<%@ Assembly Name="SchemaExplorer"%>
<%@ Import Namespace="SchemaExplorer"%>
<%-- 数据库 --%>
<%@ Property Name="SourceDatabase"  Type="SchemaExplorer.DatabaseSchema" DeepLoad="True" Optional="False" Category="需要的数据库" Description="Database"%>
<%-- 要打印的表 --%>
<%@ Property Name="Table"  Type="SchemaExplorer.TableSchema" DeepLoad="True" Optional="False" Category="需要的数据表" Description="table ." %>
<%@ Property Name="IsAll"  Type="System.Boolean" Optional="False" Category="是否生成全部表" Default="True" Description="是否生成全部表" %>
<%-- 注册实体层Model模板 --%>
<%@ Register Name="edmx_sumary" Template="edmx_sumary.cst" MergeProperties="Flase" ExcludeProperties=""%>
<script runat="template">
    //解决方案输出路径
     private string Directory = String.Empty;
    [Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]   
    [Optional, NotChecked]
    [DefaultValue("")]
    public 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.Substring(0,i)+tableName.Substring(i,1).ToLower()+tableName.Substring(i+1);
                break;
            }
        }
        return tableName;
    }
        //生成实体Entity类
    private void GenerateEntityClasses()
    {
        CodeTemplate edmx_sumaryTemplate =new edmx_sumary();
        /*
        ////生成基础BaseDAL抽象类
        string basedalDirectory = OutputDirectory +"\\DAL\\BaseDAL.cs";
        basedalTemplate.SetProperty("NM",MyNameSpace);//命名空间
        basedalTemplate.RenderToFile(basedalDirectory,true);//文件输出
        Debug.WriteLine(basedalDirectory +" 创建成功.");
        */
        
            Response.WriteLine("……………………开始生成……………………");
            string edmx_sumaryDirectory = OutputDirectory +"\\edmx_sumary.xml";
            
            //生成Service文件
            edmx_sumaryTemplate.SetProperty("SourceDatabase",SourceDatabase);
            edmx_sumaryTemplate.SetProperty("Table",Table);
            edmx_sumaryTemplate.SetProperty("IsAll",IsAll);
            edmx_sumaryTemplate.RenderToFile(edmx_sumaryDirectory,true);//文件输出
            Response.WriteLine(edmx_sumaryDirectory +" 创建成功.");
            
            Response.WriteLine("…………………… 完成生成……………………");
    }
</script>
<%
    //创建实体层Entity类
    this.GenerateEntityClasses();
    Debug.WriteLine("全部生成完成!");
    Response.WriteLine("全部生成完成!");
%>


c#新建控制台应用程序,给edmx中的字段加注释:

    class Program
    {
        static void Main(string[] args)
        {
            Work wk = new Work();
            wk.DoWork();
            Console.ReadKey();
        }
    }
    public class Work
    {
//文件都放到生成的exe同目录下执行
        public string InXmlPath = "edmx_sumary.xml";//code smith生成的注释文件
        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 = outputDoc.SelectSingleNode("/edmx:Edmx/edmx:Runtime/edmx:ConceptualModels", xmlnsManager).ChildNodes[0];
            foreach (XmlNode inNode in inList)//循环多张表注释
            {
                if (inNode.NodeType == XmlNodeType.Comment) continue;
                XmlElement inElement = (XmlElement)inNode;
                string tableName = inElement.GetAttribute("Name");
                Console.Write(tableName + "  ;  ");
                Console.WriteLine();
                XmlElement outElement = null;
                foreach (XmlNode outNodetemp in outSchemaNode.ChildNodes)//找出输入文件表节点 对应的输出文件 表节点
                {
                    if (outNodetemp.NodeType == XmlNodeType.Comment || outNodetemp.Name == "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);//删除输出文件原有的表注释
                }
                //outputDoc.Save(OutFile + "new.edmx"); return;
                foreach (XmlNode field in inElement.ChildNodes)//循环输入文件各字段
                {
                    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("Documentation", "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;//把输入文件的属性 修改到 输出文件里面
                                break;
                            }
                        }
                    }
                }
            }
            outputDoc.Save(OutFile + "new.edmx");//保存到新文件,也可以保存到原文件,最好先备份原文件。
        }
    }



tt模版中也要写代码从edmx中读取注释,现在注释已经在edmx文件中了,可以用记事本打开查看的。

关于tt读取edmx中的注释,网上代码很多 ,都可行。




版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。