ReverseEngineerCodeFirst 自定义模板
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 自定义模板的更多相关文章
- Django自定义模板
定义simple_tag步骤 一.创建templatetags文件 首先在app下创建templatetags文件:名字不许叫这个,不能改变. 二.在文件中创建一个py文件 文件名自定义 三.在创建的 ...
- 学习CodeIgniter框架之旅(一)自定义模板目录
在常用的框架本身都已经做好了分层和目录结构,但这在很多时候不满足项目的需求甚至在某些情况下变得不合理,因此很多时候需要自定义目录结构,在此就看看如果在CodeIgniter框架中自定义模板目录: 在C ...
- .NET/ASP.NETMVC 深入剖析 Model元数据、HtmlHelper、自定义模板、模板的装饰者模式(三)
阅读目录: 7.HtmlHelper.HtmlHelper<T>中的ViewModel的类型推断 8.控制ViewModel中的某个属性的呈现(使用PartialView部分视图细粒度控制 ...
- 使用requireJS,backboneJS,和underscoreJS完成自定义模板封装
使用requireJS,backboneJS,和underscoreJS完成自定义模板封装 原来的代码 当我们进行一个列表的数据填充的时候,是这样做的: //获取美食列表 function getFo ...
- DISCUZ 自定义模板
DISCUZ 自定义模板 模板安装和维护 安装新模板 将模板template打包放在对应目录:template/ 后台 -> 界面 -> 风格管理 , 安装模板 后台 -> 界面 - ...
- 谈谈yii2-gii如何自定义模板
作者:白狼 出处:http://www.manks.top/article/yii2_gii_custom_template本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位 ...
- SharePoint 2013 自定义模板页后在列表里修改不了视图
前言 最近系统从2010升级至2013,有自定义模板页.突然发现在列表中切换不了视图,让我很费解. 我尝试过以下解决方案: 去掉自定义css 去掉自定义js 禁用所有自定义功能 结果都没有效还是一样的 ...
- WPF Step By Step 自定义模板
WPF Step By Step 自定义模板 回顾 上一篇,我们简单介绍了几个基本的控件,本节我们将讲解每个控件的样式的自定义和数据模板的自定义,我们会结合项目中的具体的要求和场景来分析,给出我们实现 ...
- SublimeText插件Emmet的自定义模板
在前端界,作为快速生成代码的Emmet插件相当给力.最近在学bootstrap,需要频繁生成html头文件,我就想着自定义模板.国内只有基础教程,只好自己读英文文档了. Emmet国内基础教程地址: ...
随机推荐
- centos 设置 ip地址
linux设置ip,主要是修改/etc/sysconfig/network-scripts/ifcfg-** 里面的网卡配置文件,然后命令 service network restart 生效 自动获 ...
- Spring处理自动装配的歧义性
1.标识首选的bean 2.使用限定符@Qualifier 首先在bean的声明上添加@Qualifier 注解: @Component @Qualifier("cdtest") ...
- css3 animation 中的 steps
steps Specifies a stepping function, described above, taking two parameters. The first parameter spe ...
- python实战教程之自动扫雷
1.找到游戏窗口与坐标 #扫雷游戏窗口class_name = "TMain"title_name = "Minesweeper Arbiter "hwnd = ...
- 模态框(layer)
推荐一个好看的模态框(layer) 地址:http://layer.layui.com/ 相应列子及配置 全部来自于官网,可直接访问官网学习了解. //信息框-例1 layer.alert('见 ...
- Django - 内容总结(1)
内容整理: 1.创建django工程名称 django-admin startproject 工程名 2.创建app cd 工程名 python manage.py startapp cmdb 3.静 ...
- Asp.Mvc 常用
url转义 var address = "http://www.cnblog.com"; var a22 = Uri.EscapeDataString(address); var ...
- DP——最长上升子序列(LIS)
DP——最长上升子序列(LIS) 基本定义: 一个序列中最长的单调递增的子序列,字符子序列指的是字符串中不一定连续但先后顺序一致的n个字符,即可以去掉字符串中的部分字符,但不可改变其前后顺序. LIS ...
- CentOS7下安装ELK三件套
ELK用于分布式收集,然后elasticsearch用于分析数据,在Kibana中可以查看数据.报表. 目前公司日志数据量暂时不使用elasticsearch集群,只是用的elasticsearch单 ...
- git 删除某次指定的提交
reset命令有3种方式: 1:git reset –mixed:此为默认方式,不带任何参数的git reset,即时这种方式,它回退到某个版本,只保留源码,回退commit和index信息 2:gi ...