我在开发MVC的时候,对于大众化的利用VS中自带的插件进行CodeFrist去生成Model和Mapping来说。 CodeSimth用起来是相对的方便,就是利用模板生成相应的代码,方便开发者快速生成代码,也就类似东软代码生成器一样。我们只需设计好模板,绑定数据库,代码就自动生成了。
CodeSimth的安装包网络链接:http://pan.baidu.com/s/1i52iYAp 其中包括了安装步骤文件。
那这款软件安装好后,如何使用呢?这个,真的很好用!一键生成,不像CodeFirst那么麻烦。
首先,我们可以在本地某个硬盘下新建一个文件夹并命名为MODELS,然后再在这个文件夹下新建2个文件夹分别命名为Model和Mapping。这是为了后期配置CodeSimth做准备。对于生成Model和Mapping,没有模板文件什么都是白搭。模板文件会根据数据库中的表结构生成对应的Model和Mapping。如果是新手的话,我还是不建议去使用的这款软件,不然就真的是个码农了。
模板一:BaseTemp.cst
<span style="font-size:18px;"><%@ Template Language="C#" TargetLanguage="Text" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="sourceDatabase" Type="SchemaExplorer.DatabaseSchema" DeepLoad="True"
Optional="False" Category="数据库连接" %>
<%@ Property Name="NameSpace" Type="System.String" Category="Context" Default="mydb" Optional="true" %>
<%-- 注册实体层entity模板 --%>
<%@ Register Name="EntityTemplate" Template="EntityModel.cst" MergeProperties="False" ExcludeProperties="" %>
<%@ Register Name="EntityMapTemplate" Template="EntityMapping.cst" MergeProperties="False" 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;
}
}
private string DirectoryMapping = String.Empty;
[Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
[Optional, NotChecked]
[DefaultValue("")]
public string OutputDirectoryMapping
{
get
{
return DirectoryMapping;
}
set
{
if (value.EndsWith("\\")) value = value.Substring(0, value.Length -1);
DirectoryMapping = value;
}
}
</script>
<script runat="template">
//生成实体Entity类
private void GenerateEntityClasses()
{
CodeTemplate Template =new EntityTemplate();
CodeTemplate MapTemplate = new EntityMapTemplate();
Template.SetProperty("NameSpace", GetProperty("NameSpace"));
MapTemplate.SetProperty("ProjectName", GetProperty("NameSpace"));
foreach(TableSchema table in this.sourceDatabase.Tables)
{
string FileDirectory = OutputDirectory +"\\"+ table.Name +".cs";
//生成模板
Template.SetProperty("Table",table);
//文件输出
Template.RenderToFile(FileDirectory,true);
Debug.WriteLine(FileDirectory +" 创建成功.");
}
foreach(TableSchema table in this.sourceDatabase.Tables)
{
string FileDirectory = OutputDirectoryMapping +"\\"+ table.Name+"Map"+".cs";
//生成模板
MapTemplate.SetProperty("Table",table);
//文件输出
MapTemplate.RenderToFile(FileDirectory,true);
Debug.WriteLine(FileDirectory +" 创建成功.");
}
}
</script>
<%
//创建实体层Entity类
this.GenerateEntityClasses();
Debug.WriteLine("OK");
%></span>
模板二:EfRepository.cst
<span style="font-size:18px;"><%@ CodeTemplate Inherits="CodeTemplate" Language="C#" TargetLanguage="Text" Debug="True" ResponseEncoding="UTF-8" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="NameSpace" Type="System.String" Category="Context" Default="mydb<span style="font-family: Arial, Helvetica, sans-serif;">" Optional="true" %></span>
<%@ Property Name="UsingSpace" Type="System.String" Category="Context" Default="mydb<span style="font-family: Arial, Helvetica, sans-serif;">" Optional="true" %></span>
<%@ Property Name="Table" Type="TableSchema" DeepLoad="True"Optional="False" Category="01. Getting Started - Required"Description="Database that the tables views, and stored procedures shouldbe based on. IMPORTANT!!! If SourceTables and SourceViews are left blank, theEntire Database will then be generated." %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using <%=UsingSpace%>.Core.Data;
using <%=UsingSpace%>.Core.Domain.Models;
using <%=UsingSpace%>.Data.Data;
using <%=UsingSpace%>.Data.Repositories.IRepositories;
namespace <%=UsingSpace%>.Data.Repositories.EfRepositories
{
public class <%=Table.Name%>Repository : EfRepository<<%=Table.Name%>>, I<%=Table.Name%>Repository
{
public AssetDetailRepository(IDbContext context)
: base(context)
{
}
}
}</span>
模板三:EntityMapping.cst
<%@ CodeTemplate Inherits="CodeTemplate" Language="C#" TargetLanguage="Text" Debug="True" ResponseEncoding="UTF-8" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="ProjectName" Type="System.String" Category="Context" Default="mydb" Optional="true" %>
<%@ Property Name="Table" Type="TableSchema" DeepLoad="True"Optional="False" Category="数据库"Description="Database that the tables views, and stored procedures shouldbe based on. IMPORTANT!!! If SourceTables and SourceViews are left blank, theEntire Database will then be generated." %>
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using <%=ProjectName%>.Core.Domain.Models;
namespace <%=ProjectName%>.Data.Mapping
{
public class <%=Table.Name%>Map : EntityTypeConfiguration<<%=Table.Name%>>
{
public <%=Table.Name%>Map()
{
// Primary Key<%-- this.HasKey(t => t.<%=Table.PrimaryKey %>);--%>
<%if(Table.HasPrimaryKey){
foreach(ColumnSchema col in Table.PrimaryKey.MemberColumns){%>
this.HasKey(t => t.<%=col.Name%>);
<%}
}%>
// Properties
<%foreach (ColumnSchema col in Table.Columns)
{%>
//<%=col.Description %>
this.Property(t => t.<%=col.Name %>)
<%if(!col.AllowDBNull){%>
.IsRequired()
<% } %>
<%if(col.Size != 0 &&(col.DataType == DbType.AnsiString || col.DataType == DbType.AnsiStringFixedLength || col.DataType == DbType.String || col.DataType == DbType.StringFixedLength)) {%>
<%if(col.Size != -1){%>
.HasMaxLength(<%=col.Size%>)
<%} %>
<%}%>
<%if(col.DataType == DbType.Double || col.DataType == DbType.Decimal) {%>
.HasPrecision(<%=col.Precision%>,<%=col.Scale%>)
<%}%>
.HasColumnName("<%=col.Name%>");
<%} %>
// Table & Column Mappings
this.ToTable("<%=Table.Name%>");
}
}
}
模板四:EntityModel.cst
<%@ CodeTemplate Inherits="CodeTemplate" Language="C#" TargetLanguage="Text" Debug="True" ResponseEncoding="UTF-8" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="NameSpace" Type="System.String" Category="Context" Default="mydb" Optional="true" %>
<%@ Property Name="Table" Type="TableSchema" DeepLoad="True"Optional="False" Category="01. Getting Started - Required"Description="Database that the tables views, and stored procedures shouldbe based on. IMPORTANT!!! If SourceTables and SourceViews are left blank, theEntire Database will then be generated." %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace <%=NameSpace%>.Core.Domain.Models
{
/// <summary>
/// <%=Table.Description %>
/// </summary>
public partial class <%= Table.Name%>
{
<%foreach(ColumnSchema col in Table.Columns){ %>
/// <summary>
/// <%=col.Description %>
/// </summary>
public <%=GetDataType(col) %> <%=col.Name %> { get;set; }
<% } %>
}
}
<script runat="template">
public string GetDataType(ColumnSchema col){
string result = "";
switch(col.DataType){
case DbType.AnsiString:
case DbType.StringFixedLength:
result = "string";
break;
case DbType.Guid:
if(col.AllowDBNull){
result = "Guid?";
}else{
result = "Guid";
}
break;
case DbType.String:
result = "string";
break;
case DbType.Binary:
result = "byte[]";
break;
case DbType.Int16:
case DbType.Int32:
case DbType.Int64:
if(col.AllowDBNull){
result = "int?";
}else{
result = "int";
}
break;
case DbType.DateTime:
if(col.AllowDBNull){
result = "DateTime?";
}else{
result = "DateTime";
}
break;
case DbType.Boolean:
if(col.AllowDBNull){
result = "bool?";
}else{
result = "bool";
}
break;
case DbType.Decimal:
if(col.AllowDBNull){
result = "decimal?";
}else{
result = "decimal";
}
break;
case DbType.Double:
if(col.AllowDBNull){
result = "double?";
}else{
result = "double";
}
break;
}
return result;
}
</script>
模板五:IRepository.cst
<%@ CodeTemplate Inherits="CodeTemplate" Language="C#" TargetLanguage="Text" Debug="True" ResponseEncoding="UTF-8" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="NameSpace" Type="System.String" Category="Context" Default="mydb" Optional="true" %>
<%@ Property Name="UsingSpace" Type="System.String" Category="Context" Default="mydb" Optional="true" %>
<%@ Property Name="Table" Type="TableSchema" DeepLoad="True"Optional="False" Category="01. Getting Started - Required"Description="Database that the tables views, and stored procedures shouldbe based on. IMPORTANT!!! If SourceTables and SourceViews are left blank, theEntire Database will then be generated." %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using <%=UsingSpace%>.Core.Data;
using <%=UsingSpace%>.Core.Domain.Models;
namespace <%=UsingSpace%>.Data.Repositories.IRepositories
{
public interface I<%=Table.Name%>Repository : IRepository<<%=Table.Name%>>
{
}
}
然后把五个模板文件拷到CodeSimth软件下Template Explorer下的My Templates文件夹下,然后为设置连接到某个本地数据库(仅包含架构)。为其配置model生成指向之前新建的文件夹Model的路径,把mapping生成指向之前新建的文件夹Mapping的路径。然后Click Generate按钮,一键生成Model和Mapping,然后把对应生成的model和Mapping拷到对应的文件下。(其中如果利用Pd去生成数据库架构的话,还可以其中编写Comments 注释,之后代码中也会生成对应的注释,方便后期开发的维护。)
这就大大减轻了工作量。
如果要用CodeSimth去生成Model和Mapping,我们也要安装另外两个软件 PD(PowerDesigner)和SqlSever数据库管理工具(应该也可以使用navicat这个软件)。Pd是用来设计数据库的就是设计数据库的架构,SqlSever这个软件用来管理数据库的数据的。这两个软件之后会再写文章,介绍一下。