1.在你要生成的项目里面在根目录下面添加CodeTemplates文件夹,并在该文件夹下面创建子文件夹ReverseEngineerCodeFirst

2.在ReverseEngineerCodeFirst目录下面新建一下几个文件:

  • Context.tt 1 <#@ template hostspecific="true" language="C#" #>
  •  <#@ include file="EF.Utility.CS.ttinclude" #><#@
    output extension=".cs" encoding="UTF-8" #><# var efHost = (EfTextTemplateHost)Host;
    var code = new CodeGenerationTools(this); #>
    //------------------------------------------------------------------------------
    // <auto-generated>
    // 此代码由工具生成。
    // 对此文件的更改可能会导致不正确的行为,并且如果
    // 重新生成代码,这些更改将会丢失。
    // </auto-generated>
    // <copyright file="<#= efHost.EntityContainer.Name #>.cs">
    // Copyright(c)2015 rights reserved.
    // CLR版本:4.0.30319.239
    18 // 生成时间:<#= DateTime.Now.ToString("yyyy-MM-dd HH:mm") #>
    // </copyright>
    //------------------------------------------------------------------------------ using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using <#= code.EscapeNamespace(efHost.MappingNamespace) #>; namespace <#= code.EscapeNamespace(efHost.Namespace) #>
    {
    public partial class <#= efHost.EntityContainer.Name #> : DbContext
    {
    static <#= efHost.EntityContainer.Name #>()
    {
    Database.SetInitializer<<#= efHost.EntityContainer.Name #>>(null);
    } public <#= efHost.EntityContainer.Name #>()
    : base("Name=<#= efHost.EntityContainer.Name #>")
    {
    } <#
    var summary="";
    foreach (var set in efHost.EntityContainer.BaseEntitySets.OfType<EntitySet>())
    {
    if(set.Documentation !=null && set.Documentation.Summary!=null)
    summary=set.Documentation.Summary; else if(set.Documentation !=null && set.Documentation.LongDescription!=null)
    summary=set.Documentation.LongDescription;
    else
    summary=string.Format("[{0}]", set.ElementType.Name);
    #>
    /// <summary>
    /// <#= summary #>
    /// </summary>
    public DbSet<<#= set.ElementType.Name #>> <#= set.Name #> { get; set; }
    <#
    }
    #> protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    <#
    foreach (var set in efHost.EntityContainer.BaseEntitySets.OfType<EntitySet>())
    {
    #>
    modelBuilder.Configurations.Add(new <#= set.ElementType.Name #>Map());
    <#
    }
    #>
    }
    }
    }
  • Entity.tt
  •  <#@ template hostspecific="true" language="C#" #>
    <#@ include file="EF.Utility.CS.ttinclude" #><#@
    output extension=".cs" encoding="UTF-8" #><# var efHost = (EfTextTemplateHost)Host;
    var code = new CodeGenerationTools(this); #>
    //------------------------------------------------------------------------------
    // <auto-generated>
    // 此代码由工具生成。
    // 对此文件的更改可能会导致不正确的行为,并且如果
    // 重新生成代码,这些更改将会丢失。
    // </auto-generated>
    // <copyright file="<#= efHost.EntityType.Name #>.cs">
    // Copyright(c)2015 rights reserved.
    // CLR版本:4.0.30319.239
    20 // 生成时间:<#= DateTime.Now.ToString("yyyy-MM-dd HH:mm") #>
    // </copyright>
    //------------------------------------------------------------------------------ using System;
    using System.Collections.Generic;
    using XXXX.EF;
    using XXXX.EF.Base;
    using XXXX.ToolT4; <#
    var summary="";
    var entity=efHost.EntityType;
    if(entity.Documentation !=null && entity.Documentation.Summary!=null)
    summary=entity.Documentation.Summary; else if(entity.Documentation !=null && entity.Documentation.LongDescription!=null)
    summary=entity.Documentation.LongDescription;
    else
    summary=string.Format("[{0}]", entity.Name); #> namespace <#= code.EscapeNamespace(efHost.Namespace) #>
    {
    /// <summary>
    /// <#= summary#>
    /// </summary>
    [Serializable]
    public partial class <#= efHost.EntityType.Name #> : BaseEntity
    {
    <#
    var collectionNavigations = efHost.EntityType.NavigationProperties.Where(
    np => np.DeclaringType == efHost.EntityType
    && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); // Add a ctor to initialize any collections
    if (collectionNavigations.Any())
    {
    #>
    /// <summary>
    /// 构造函数
    /// </summary>
    public <#= code.Escape(efHost.EntityType) #>()
    {
    <#
    foreach (var navProperty in collectionNavigations)
    {
    #>
    this.<#= code.Escape(navProperty) #> = new List<<#= code.Escape(navProperty.ToEndMember.GetEntityType()) #>>();
    <#
    }
    #>
    } <#
    } foreach (var property in efHost.EntityType.Properties)
    {
    var typeUsage = code.Escape(property.TypeUsage); // Fix-up spatial types for EF6
    if (efHost.EntityFrameworkVersion >= new Version(, )
    && typeUsage.StartsWith("System.Data.Spatial."))
    {
    typeUsage = typeUsage.Replace(
    "System.Data.Spatial.",
    "System.Data.Entity.Spatial.");
    }
    if(property.Documentation !=null && property.Documentation.Summary!=null)
    summary=property.Documentation.Summary; else if(property.Documentation !=null && property.Documentation.LongDescription!=null)
    summary=property.Documentation.LongDescription;
    else
    summary=string.Format("[{0}]", property.Name); #>
    /// <summary>
    /// <#= summary#>
    /// </summary>
    <#= Accessibility.ForProperty(property) #> <#= typeUsage #> <#= code.Escape(property) #> { get; set; }
    <#
    } foreach (var navProperty in efHost.EntityType.NavigationProperties.Where(np => np.DeclaringType == efHost.EntityType))
    {
    if (navProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
    {
    #>
    /// <summary>
    /// 导航集合:<#= navProperty#>
    /// </summary>
    public virtual ICollection<<#= code.Escape(navProperty.ToEndMember.GetEntityType()) #>> <#= code.Escape(navProperty) #> { get; set; }
    <#
    }
    else
    {
    #>
    /// <summary>
    /// 导航属性:<#= navProperty#>
    /// </summary>
    public virtual <#= code.Escape(navProperty.ToEndMember.GetEntityType()) #> <#= code.Escape(navProperty) #> { get; set; }
    <#
    }
    }
    #>
    }
    }
  • Mapping.tt
  • <#@ template hostspecific="true" language="C#" #>
    <#@ include file="EF.Utility.CS.ttinclude" #><#@
    output extension=".cs" encoding="UTF-8" #><# var efHost = (EfTextTemplateHost)Host;
    var code = new CodeGenerationTools(this);
    #> //------------------------------------------------------------------------------
    // <auto-generated>
    // 此代码由工具生成。
    // 对此文件的更改可能会导致不正确的行为,并且如果
    // 重新生成代码,这些更改将会丢失。
    // </auto-generated>
    // <copyright file="<#= efHost.EntityType.Name #>Map.cs">
    // Copyright(c)2015 rights reserved.
    // CLR版本:4.0.30319.239
    // 生成时间:<#= DateTime.Now.ToString("yyyy-MM-dd HH:mm") #>
    // </copyright>
    //------------------------------------------------------------------------------ <#
    if (efHost.EntityFrameworkVersion >= new Version(, ))
    {
    #>
    using System.ComponentModel.DataAnnotations.Schema;
    <#
    }
    else
    {
    #>
    using System.ComponentModel.DataAnnotations;
    <#
    }
    #>
    using System.Data.Entity.ModelConfiguration; namespace <#= code.EscapeNamespace(efHost.Namespace) #>
    {
    public class <#= efHost.EntityType.Name #>Map : EntityTypeConfiguration<<#= efHost.EntityType.Name #>>
    {
    public <#= efHost.EntityType.Name #>Map()
    {
    // Primary Key
    <#
    if (efHost.EntityType.KeyMembers.Count() == )
    {
    #>
    this.HasKey(t => t.<#= efHost.EntityType.KeyMembers.Single().Name #>);
    <#
    }
    else
    {
    #>
    this.HasKey(t => new { <#= string.Join(", ", efHost.EntityType.KeyMembers.Select(m => "t." + m.Name)) #> });
    <#
    }
    #> // Properties
    <#
    foreach (var prop in efHost.EntityType.Properties)
    {
    var type = (PrimitiveType)prop.TypeUsage.EdmType;
    var isKey = efHost.EntityType.KeyMembers.Contains(prop);
    var storeProp = efHost.PropertyToColumnMappings[prop];
    var sgpFacet = storeProp.TypeUsage.Facets.SingleOrDefault(f => f.Name == "StoreGeneratedPattern");
    var storeGeneratedPattern = sgpFacet == null
    ? StoreGeneratedPattern.None
    : (StoreGeneratedPattern)sgpFacet.Value; var configLines = new List<string>(); if (type.ClrEquivalentType == typeof(int)
    || type.ClrEquivalentType == typeof(decimal)
    || type.ClrEquivalentType == typeof(short)
    || type.ClrEquivalentType == typeof(long))
    {
    if (isKey && storeGeneratedPattern != StoreGeneratedPattern.Identity)
    {
    configLines.Add(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)");
    }
    else if ((!isKey || efHost.EntityType.KeyMembers.Count > ) && storeGeneratedPattern == StoreGeneratedPattern.Identity)
    {
    configLines.Add(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)");
    }
    } if (type.ClrEquivalentType == typeof(string)
    || type.ClrEquivalentType == typeof(byte[]))
    {
    if (!prop.Nullable)
    {
    configLines.Add(".IsRequired()");
    } var unicodeFacet = (Facet)prop.TypeUsage.Facets.SingleOrDefault(f => f.Name == "IsUnicode");
    if(unicodeFacet != null && !(bool)unicodeFacet.Value)
    {
    configLines.Add(".IsUnicode(false)");
    } var fixedLengthFacet = (Facet)prop.TypeUsage.Facets.SingleOrDefault(f => f.Name == "FixedLength");
    if (fixedLengthFacet != null && (bool)fixedLengthFacet.Value)
    {
    configLines.Add(".IsFixedLength()");
    } var maxLengthFacet = (Facet)prop.TypeUsage.Facets.SingleOrDefault(f => f.Name == "MaxLength");
    if (maxLengthFacet != null && !maxLengthFacet.IsUnbounded)
    {
    configLines.Add(string.Format(".HasMaxLength({0})", maxLengthFacet.Value)); if (storeGeneratedPattern == StoreGeneratedPattern.Computed
    && type.ClrEquivalentType == typeof(byte[])
    && (int)maxLengthFacet.Value == )
    {
    configLines.Add(".IsRowVersion()");
    }
    }
    } if(configLines.Any())
    {
    #>
    this.Property(t => t.<#= prop.Name #>)
    <#= string.Join("\r\n ", configLines) #>; <#
    }
    } var tableSet = efHost.TableSet;
    var tableName = (string)tableSet.MetadataProperties["Table"].Value
    ?? tableSet.Name;
    var schemaName = (string)tableSet.MetadataProperties["Schema"].Value;
    #>
    // Table & Column Mappings
    this.ToTable("<#= tableName #>");
    <#
    foreach (var property in efHost.EntityType.Properties)
    {
    if(property.TypeUsage.EdmType is PrimitiveType && ((PrimitiveType)property.TypeUsage.EdmType).PrimitiveTypeKind == PrimitiveTypeKind.Decimal)
    {
    var jdLen = property.TypeUsage.Facets[].Value;
    var jdXsv = property.TypeUsage.Facets[].Value;
    #>
    this.Property(t => t.<#=property.Name #>).HasColumnName("<#=efHost.PropertyToColumnMappings[property].Name #>").HasPrecision(<#=jdLen#>,<#=jdXsv#>);
    <#
    }
    else{
    #>
    this.Property(t => t.<#=property.Name #>).HasColumnName("<#=efHost.PropertyToColumnMappings[property].Name #>");
    <#
    }
    } // Find m:m relationshipsto configure
    var manyManyRelationships = efHost.EntityType.NavigationProperties
    .Where(np => np.DeclaringType == efHost.EntityType
    && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many
    && np.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many
    && np.RelationshipType.RelationshipEndMembers.First() == np.FromEndMember); // <- ensures we only configure from one end // Find FK relationships that this entity is the dependent of
    var fkRelationships = efHost.EntityType.NavigationProperties
    .Where(np => np.DeclaringType == efHost.EntityType
    && ((AssociationType)np.RelationshipType).IsForeignKey
    && ((AssociationType)np.RelationshipType).ReferentialConstraints.Single().ToRole == np.FromEndMember); if(manyManyRelationships.Any() || fkRelationships.Any())
    {
    #> // Relationships
    <#
    foreach (var navProperty in manyManyRelationships)
    {
    var otherNavProperty = navProperty.ToEndMember.GetEntityType().NavigationProperties.Where(n => n.RelationshipType == navProperty.RelationshipType && n != navProperty).Single();
    var association = (AssociationType)navProperty.RelationshipType;
    var mapping = efHost.ManyToManyMappings[association];
    var item1 = mapping.Item1;
    var mappingTableName = (string)mapping.Item1.MetadataProperties["Table"].Value
    ?? item1.Name;
    var mappingSchemaName = (string)item1.MetadataProperties["Schema"].Value; // Need to ensure that FKs are decalred in the same order as the PK properties on each principal type
    var leftType = (EntityType)navProperty.DeclaringType;
    var leftKeyMappings = mapping.Item2[navProperty.FromEndMember];
    var leftColumns = string.Join(", ", leftType.KeyMembers.Select(m => "\"" + leftKeyMappings[m] + "\""));
    var rightType = (EntityType)otherNavProperty.DeclaringType;
    var rightKeyMappings = mapping.Item2[otherNavProperty.FromEndMember];
    var rightColumns = string.Join(", ", rightType.KeyMembers.Select(m => "\"" + rightKeyMappings[m] + "\""));
    #>
    this.HasMany(t => t.<#= code.Escape(navProperty) #>)
    .WithMany(t => t.<#= code.Escape(otherNavProperty) #>)
    .Map(m =>
    {
    m.ToTable("<#= mappingTableName #>");
    m.MapLeftKey(<#= leftColumns #>);
    m.MapRightKey(<#= rightColumns #>);
    }); <#
    } foreach (var navProperty in fkRelationships)
    {
    var otherNavProperty = navProperty.ToEndMember.GetEntityType().NavigationProperties.Where(n => n.RelationshipType == navProperty.RelationshipType && n != navProperty).Single();
    var association = (AssociationType)navProperty.RelationshipType; if (navProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One)
    {
    #>
    this.HasRequired(t => t.<#= code.Escape(navProperty) #>)
    <#
    }
    else
    {
    #>
    this.HasOptional(t => t.<#= code.Escape(navProperty) #>)
    <#
    } if(navProperty.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
    {
    #>
    .WithMany(t => t.<#= code.Escape(otherNavProperty) #>)
    <#
    if(association.ReferentialConstraints.Single().ToProperties.Count == )
    {
    #>
    .HasForeignKey(d => d.<#= association.ReferentialConstraints.Single().ToProperties.Single().Name #>);
    <#
    }
    else
    {
    #>
    .HasForeignKey(d => new { <#= string.Join(", ", association.ReferentialConstraints.Single().ToProperties.Select(p => "d." + p.Name)) #> });
    <#
    }
    }
    else
    {
    // NOTE: We can assume that this is a required:optional relationship
    // as EDMGen will never create an optional:optional relationship
    // because everything is one:many except PK-PK relationships which must be required
    #>
    .WithOptional(t => t.<#= code.Escape(otherNavProperty) #>);
    <#
    }
    }
    #> <#
    }
    #>
    }
    }
    }
  • BaseEntity.cs
  • using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema; namespace XXXX.EF.Base
    {
    /// <summary>
    /// 抽象实体类型:可用作DbFirst使用以作为Entiry基类
    /// </summary>
    public abstract class BaseEntity
    {
    }
    }
  • T4ModelInfo.cs
  • using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Reflection; namespace XXXX.ToolT4
    {
    /// <summary>
    /// T4实体模型信息类
    /// </summary>
    public class T4ModelInfo
    {
    /// <summary>
    /// 获取 模型所在模块名称
    /// </summary>
    public string ModuleName { get; private set; } /// <summary>
    /// 获取 模型名称
    /// </summary>
    public string Name { get; private set; } /// <summary>
    /// 获取 模型描述
    /// </summary>
    public string Description { get; private set; } /// <summary>
    /// 属性集合
    /// </summary>
    public IEnumerable<PropertyInfo> Properties { get; private set; } public T4ModelInfo(Type modelType)
    {
    var @namespace = modelType.Namespace;
    if (@namespace == null)
    {
    return;
    }
    var index = @namespace.LastIndexOf('.') + ;
    ModuleName = @namespace.Substring(index, @namespace.Length - index);
    Name = modelType.Name;
    var descAttributes = modelType.GetCustomAttributes(typeof(DescriptionAttribute), true);
    Description = descAttributes.Length == ? ((DescriptionAttribute)descAttributes[]).Description : Name;
    Properties = modelType.GetProperties();
    }
    }
    }

有了上传代码借助于EntityReverseCode就可以生成我们需要的实体类,实体映射类

ReverseEngineerCodeFirst 自定义模板的更多相关文章

  1. Django自定义模板

    定义simple_tag步骤 一.创建templatetags文件 首先在app下创建templatetags文件:名字不许叫这个,不能改变. 二.在文件中创建一个py文件 文件名自定义 三.在创建的 ...

  2. 学习CodeIgniter框架之旅(一)自定义模板目录

    在常用的框架本身都已经做好了分层和目录结构,但这在很多时候不满足项目的需求甚至在某些情况下变得不合理,因此很多时候需要自定义目录结构,在此就看看如果在CodeIgniter框架中自定义模板目录: 在C ...

  3. .NET/ASP.NETMVC 深入剖析 Model元数据、HtmlHelper、自定义模板、模板的装饰者模式(三)

    阅读目录: 7.HtmlHelper.HtmlHelper<T>中的ViewModel的类型推断 8.控制ViewModel中的某个属性的呈现(使用PartialView部分视图细粒度控制 ...

  4. 使用requireJS,backboneJS,和underscoreJS完成自定义模板封装

    使用requireJS,backboneJS,和underscoreJS完成自定义模板封装 原来的代码 当我们进行一个列表的数据填充的时候,是这样做的: //获取美食列表 function getFo ...

  5. DISCUZ 自定义模板

    DISCUZ 自定义模板 模板安装和维护 安装新模板 将模板template打包放在对应目录:template/ 后台 -> 界面 -> 风格管理 , 安装模板 后台 -> 界面 - ...

  6. 谈谈yii2-gii如何自定义模板

    作者:白狼 出处:http://www.manks.top/article/yii2_gii_custom_template本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位 ...

  7. SharePoint 2013 自定义模板页后在列表里修改不了视图

    前言 最近系统从2010升级至2013,有自定义模板页.突然发现在列表中切换不了视图,让我很费解. 我尝试过以下解决方案: 去掉自定义css 去掉自定义js 禁用所有自定义功能 结果都没有效还是一样的 ...

  8. WPF Step By Step 自定义模板

    WPF Step By Step 自定义模板 回顾 上一篇,我们简单介绍了几个基本的控件,本节我们将讲解每个控件的样式的自定义和数据模板的自定义,我们会结合项目中的具体的要求和场景来分析,给出我们实现 ...

  9. SublimeText插件Emmet的自定义模板

    在前端界,作为快速生成代码的Emmet插件相当给力.最近在学bootstrap,需要频繁生成html头文件,我就想着自定义模板.国内只有基础教程,只好自己读英文文档了. Emmet国内基础教程地址: ...

随机推荐

  1. PHP 之phpqrcode类库生成二维码

    <?php /** * Created by PhpStorm. * User: 25754 * Date: 2019/6/4 * Time: 15:53 */ include "./ ...

  2. js 字符串,数组扩展

    console.log(Array.prototype.sort)//ƒ substring() { [native code] } console.log(String.prototype.subs ...

  3. asp网站中使用百度ueditor教程.txt

    1.根据网站类型及编码选择相应的ueditor版本,如我的网站编码为gb2312,则选择ueditor 1.43 asp gbk版.2.本机IE浏览器应为8.0或以上,8.0以下的ueditor 1. ...

  4. CentOS 7安装JDK 1.8

    1. 首先查看当前Linux系统是否安装Java ``` rpm -qa | grep java ``` 2. 如果列表显示有,则使用命令将其卸载 rpm -e --nodeps 要卸载的软件名 或 ...

  5. mysql-索引、导入、导出、备份、恢复

    1.索引 索引是一种与表有关的结构,它的作用相当于书的目录,可以根据目录中的页码快速找到所需的内容. 当表中有大量记录时,若要对表进行查询,没有索引的情况是全表搜索:将所有记录一一取出,和查询条件进行 ...

  6. Alliances

    树国是一个有n个城市的国家,城市编号为1∼n.连接这些城市的道路网络形如一棵树, 即任意两个城市之间有恰好一条路径.城市中有k个帮派,编号为1∼k.每个帮派会占据一些城市,以进行非法交易.有时帮派之间 ...

  7. VM 与主机不通的解决方法

    [root@localhost network-scripts]# ping 192.168.1.222 PING 192.168.1.222 (192.168.1.222) 56(84) bytes ...

  8. [转]wcf系列学习——服务托管

    今天是系列的终结篇,当然要分享一下wcf的托管方面的知识. wcf中托管服务一般有一下四种: Console寄宿:             利于开发调试,但不是生产环境中的最佳实践. winform寄 ...

  9. JCE, Java Cryptography Extension

    JCE, Java Cryptography Extension Java 8 JCE下载地址: http://www.oracle.com/technetwork/java/javase/downl ...

  10. [Node.js] Setup Local Configuration with Node.js Applications

    Github To stop having to change configuration settings in production code and to stop secure informa ...