转移.net core 3.1,为.NET 5做准备

This commit is contained in:
ÂëÉñ
2020-10-22 14:59:36 +08:00
parent fd9bca23a7
commit a35d596237
1080 changed files with 175912 additions and 185681 deletions

View File

@@ -0,0 +1,226 @@
<%--
Author: yubaolee
Description: 用于生成OpenAuth.WebApi接口相关代码包括controller/app/实体/dbcontext
--%>
<%@ Template Language="C#" TargetLanguage="Text" Debug="True" OutputType="Normal" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="CodeSmith.CustomProperties" %>
<%@ Assembly Name="Mono.Cecil" Path="..\Common" %>
<%@ Assembly Name="ICSharpCode.NRefactory" Path="..\Common" %>
<%@ Assembly Name="ICSharpCode.NRefactory.CSharp" Path="..\Common" %>
<%@ Assembly Src="Internal\Model.cs" %>
<%@ Assembly Src="Internal\Extensions.cs" %>
<%@ Assembly Src="Internal\Generator.cs" %>
<%@ Assembly Src="Internal\Parser.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="System.Diagnostics" %>
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="WholeDb"
Type="System.Boolean"
Category="1.Database"
Default="true"
Description="是否直接生成选定数据库中的所有表" %>
<%@ Property Name="HeaderModel"
Type="System.Boolean"
Category="1.Database"
Default="true"
Description="是否为启用头表模式,即类似‘入库订单’界面" %>
<%@ Property Name="SourceDatabase"
Type="SchemaExplorer.DatabaseSchema"
Category="1.Database"
Description="The source database." %>
<%@ Property Name="SourceTables"
Type="SchemaExplorer.TableSchemaCollection"
Category="1.Database" Description="可以选择一个或多个表使用Ctrl键" %>
<%@ Property Name="directory"
Type="System.String"
Default=".\"
Optional="True"
Description="代码生成路径"
Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
<%@ Property Name="ContextNamespace"
Type="System.String"
Category="2.Class"
Default="OpenAuth.Repository"
OnChanged="OnContextNamespaceChanged"
Description="DbContext默认命名空间尽量不要更改"%>
<%@ Property Name="EntityNamespace"
Type="System.String"
Default="OpenAuth.Repository.Domain"
Category="2.Class"
Description="实体默认命名空间,尽量不要更改"%>
<%@ Register Name="EntityGeneratedClass"
Template="Internal\Entity.Generated.cst"
MergeProperties="False" %>
<%@ Register Name="ContextGeneratedClass"
Template="Internal\Context.Generated.cst"
MergeProperties="True" %>
<%@ Register Name="ApplicationGenerateClass"
Template="ApiGenerate\Application.cst"
MergeProperties="False" %>
<%@ Register Name="RequestGenerateClass"
Template="ApiGenerate\Request.cst"
MergeProperties="False" %>
<%@ Register Name="ModifyReqGenerateClass"
Template="ApiGenerate\ModifyReq.cst"
MergeProperties="False" %>
<%@ Register Name="ControllerGenerateClass"
Template="ApiGenerate\Controller.cst"
MergeProperties="False" %>
开始创建OpenAuth.Core WebApi相关代码 ...
<% Generate(); %>
<script runat="template">
private TableSchemaCollection tables;
public void Generate()
{
Stopwatch watch = Stopwatch.StartNew();
string outputDirectory = Path.GetFullPath(directory);
if(WholeDb){
tables = SourceDatabase.Tables;
}
else{
tables = SourceTables;
}
CreateEntityClasses();
CreateControllerClass();
CreateApplicationClass();
CreateReqClass();
CreateContextClass();
watch.Stop();
Response.WriteLine("Generate Time: " + watch.ElapsedMilliseconds + " ms");
}
//创建实体类
public void CreateEntityClasses()
{
EntityGeneratedClass generatedClass = this.Create<EntityGeneratedClass>();
this.CopyPropertiesTo(generatedClass);
foreach(TableSchema table in tables)
{
string className = table.Name;
string generatedFile = Path.GetFullPath(directory) + "OpenAuth.Repository\\Domain\\" + className + ".cs";
generatedClass.Table = table;
Response.WriteLine("已生成"+generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true);
}
}
//创建DbContext
public void CreateContextClass()
{
ContextGeneratedClass generatedClass = this.Create<ContextGeneratedClass>();
this.CopyPropertiesTo(generatedClass);
string dbContextName;
if(WholeDb){
dbContextName = SourceDatabase.Name.ToSafeName();
}
else{
dbContextName = SourceTables.First().Database.Name.ToSafeName();
}
dbContextName = StringUtil.ToPascalCase(dbContextName);
string generatedFile = "OpenAuth.Repository\\" + dbContextName + "Context.cs";
Response.WriteLine("重要提示!!!!把下面内容添加到"+generatedFile+"对应的位置中,千万不要直接覆盖!!!");
Response.WriteLine(generatedClass.RenderToString());
}
//创建控制器,如UserManagerController.cs
public void CreateControllerClass()
{
ControllerGenerateClass generatedClass = this.Create<ControllerGenerateClass>();
this.CopyPropertiesTo(generatedClass);
foreach(TableSchema table in tables)
{
string generatedFile = Path.GetFullPath(directory) + "OpenAuth.WebApi\\Controllers\\"+ table.Name + "sController.cs";
generatedClass.ModuleName = table.Name;
Response.WriteLine("已生成"+generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true);
}
}
//创建APP层,如UserManagerApp.cs
public void CreateApplicationClass()
{
ApplicationGenerateClass generatedClass = this.Create<ApplicationGenerateClass>();
this.CopyPropertiesTo(generatedClass);
foreach(TableSchema table in tables)
{
string generatedFile = Path.GetFullPath(directory) + "OpenAuth.App\\"+ table.Name + "App.cs";
generatedClass.Table = table;
//generatedClass.Entity = entity;
Response.WriteLine("已生成"+generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true);
}
}
//创建请求参数,如QueryUserListReq.cs
public void CreateReqClass()
{
RequestGenerateClass generatedClass = this.Create<RequestGenerateClass>();
this.CopyPropertiesTo(generatedClass);
foreach(TableSchema table in tables)
{
string generatedFile = Path.GetFullPath(directory) + "OpenAuth.App\\Request\\Query"+ table.Name + "ListReq.cs";
generatedClass.ModuleName = table.Name;
Response.WriteLine("已生成"+generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true);
}
//生成编辑修改的请求参数
ModifyReqGenerateClass modifyReqGenerateClass = this.Create<ModifyReqGenerateClass>();
this.CopyPropertiesTo(modifyReqGenerateClass);
foreach(TableSchema table in tables)
{
string generatedFile = Path.GetFullPath(directory) + "OpenAuth.App\\Request\\AddOrUpdate"+ table.Name + "Req.cs";
modifyReqGenerateClass.Table = table;
Response.WriteLine("已生成"+generatedFile);
modifyReqGenerateClass.RenderToFile(generatedFile, generatedFile, true);
}
}
private void OnContextNamespaceChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(ContextNamespace))
return;
if (string.IsNullOrEmpty(EntityNamespace))
EntityNamespace = ContextNamespace + ".Domain";
}
</script>

View File

@@ -0,0 +1,185 @@
<%--
Name: Database Table Properties
Author: yubaolee
Description: Create a list of properties from a database table
--%>
<%@ CodeTemplate Language="C#" Encoding="utf-8" TargetLanguage="C#" Debug="True" Description="应用层" %>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="Table"
Type="SchemaExplorer.TableSchema" %>
<%@ Property Name="HeaderModel"
Type="System.Boolean"
Category="1.Database"
Default="true"
Description="是否为启用头表模式,即类似‘入库订单’界面" %>
using System;
using System.Linq;
using Infrastructure;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Interface;
namespace OpenAuth.App
{
public class <%=Table.Name%>App : BaseApp<<%=Table.Name%>>
{
private RevelanceManagerApp _revelanceApp;
/// <summary>
/// 加载列表
/// </summary>
public TableData Load(Query<%=Table.Name%>ListReq request)
{
var loginContext = _auth.GetCurrentUser();
if (loginContext == null)
{
throw new CommonException("登录已过期", Define.INVALID_TOKEN);
}
var properties = loginContext.GetProperties("<%=Table.Name%>");
if (properties == null || properties.Count == 0)
{
throw new Exception("当前登录用户没有访问该模块字段的权限,请联系管理员配置");
}
var result = new TableData();
var objs = UnitWork.Find<<%=Table.Name%>>(null);
if (!string.IsNullOrEmpty(request.key))
{
objs = objs.Where(u => u.Id.Contains(request.key));
}
var propertyStr = string.Join(',', properties.Select(u => u.Key));
result.columnHeaders = properties;
result.data = objs.OrderBy(u => u.Id)
.Skip((request.page - 1) * request.limit)
.Take(request.limit).Select($"new ({propertyStr})");
result.count = objs.Count();
return result;
}
<%
if(Table.Name.Contains("Tbl") && (!Table.Name.Contains("Dtbl")) && this.HeaderModel){
var dtblName = Table.Name.Replace("Tbl","Dtbl"); //明细表的表名
%>
public void Add(AddOrUpdate<%=Table.Name%>Req req)
{
var obj = req.MapTo<<%=Table.Name%>>();
//todo:补充或调整自己需要的字段
obj.CreateTime = DateTime.Now;
var user = _auth.GetCurrentUser().User;
obj.CreateUserId = user.Id;
obj.CreateUserName = user.Name;
UnitWork.Add(obj);
if (req.<%=dtblName%>Reqs != null && req.<%=dtblName%>Reqs.Any())
{
foreach (var detail in req.<%=dtblName%>Reqs)
{
detail.ForeignKeyId = obj.Id; //todo:调整自己的明细表外键
_<%=dtblName%>App.AddNoSave(detail);
}
}
UnitWork.Save();
}
public void Update(AddOrUpdate<%=Table.Name%>Req obj)
{
var user = _auth.GetCurrentUser().User;
if (obj.<%=dtblName%>Reqs != null && obj.<%=dtblName%>Reqs.Any())
{
//id为空的添加
foreach (var detail in obj.<%=dtblName%>Reqs.Where(u =>string.IsNullOrEmpty(u.Id)))
{
detail.ForeignKeyId = obj.Id; //todo:调整自己的明细表外键
_<%=dtblName%>App.AddNoSave(detail);
}
//id比数据库少的删除
var containids = obj.<%=dtblName%>Reqs.Select(u => u.Id)
.Where(u =>!string.IsNullOrEmpty(u)).ToList();
if (containids.Any())
{
UnitWork.Delete<<%=dtblName%>>(u =>(!containids.Contains(u.Id)) && u.ForeignKeyId == obj.Id); //todo:调整自己的明细表外键
}
//更新id相同的
foreach (var detail in obj.<%=dtblName%>Reqs.Where(u =>!string.IsNullOrEmpty(u.Id)))
{
_<%=dtblName%>App.Update(detail);
}
}
UnitWork.Update<<%=Table.Name%>>(u => u.Id == obj.Id, u => new <%=Table.Name%>
{
<% foreach(ColumnSchema p in Table.Columns) {
if(p.IsPrimaryKeyMember) continue;
%>
<%= p.Name%> = obj.<%= p.Name%>,
<% } %>
UpdateTime = DateTime.Now,
UpdateUserId = user.Id,
UpdateUserName = user.Name
//todo:补充或调整自己需要的字段
});
UnitWork.Save();
}
<%
}else{ %>
public void Add(AddOrUpdate<%=Table.Name%>Req req)
{
var obj = req.MapTo<<%=Table.Name%>>();
//todo:补充或调整自己需要的字段
obj.CreateTime = DateTime.Now;
var user = _auth.GetCurrentUser().User;
obj.CreateUserId = user.Id;
obj.CreateUserName = user.Name;
Repository.Add(obj);
}
public void Update(AddOrUpdate<%=Table.Name%>Req obj)
{
var user = _auth.GetCurrentUser().User;
UnitWork.Update<<%=Table.Name%>>(u => u.Id == obj.Id, u => new <%=Table.Name%>
{
<% foreach(ColumnSchema p in Table.Columns) {
if(p.IsPrimaryKeyMember) continue;
%>
<%= p.Name%> = obj.<%= p.Name%>,
<% } %>
UpdateTime = DateTime.Now,
UpdateUserId = user.Id,
UpdateUserName = user.Name
//todo:补充或调整自己需要的字段
});
}
<%
}
%>
public <%=Table.Name%>App(IUnitWork unitWork, IRepository<<%=Table.Name%>> repository,
RevelanceManagerApp app, IAuth auth) : base(unitWork, repository,auth)
{
_revelanceApp = app;
}
}
}

View File

@@ -0,0 +1,122 @@
<%--
Name: Database Table Properties
Author: yubaolee
Description: Create a list of properties from a database table
--%>
<%@ CodeTemplate Language="C#" Encoding="utf-8" TargetLanguage="C#" Debug="True" Description="控制器" %>
<%@ Property Name="ModuleName" Type="String" Category="Context" Description="模块名称" %>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
using System;
using Infrastructure;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;
namespace OpenAuth.WebApi.Controllers
{
/// <summary>
/// <%=ModuleName%>操作
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class <%=ModuleName%>sController : ControllerBase
{
private readonly <%=ModuleName%>App _app;
//获取详情
[HttpGet]
public Response<<%=ModuleName%>> Get(string id)
{
var result = new Response<<%=ModuleName%>>();
try
{
result.Result = _app.Get(id);
}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.InnerException?.Message ?? ex.Message;
}
return result;
}
//添加
[HttpPost]
public Response Add(AddOrUpdate<%=ModuleName%>Req obj)
{
var result = new Response();
try
{
_app.Add(obj);
}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.InnerException?.Message ?? ex.Message;
}
return result;
}
//修改
[HttpPost]
public Response Update(AddOrUpdate<%=ModuleName%>Req obj)
{
var result = new Response();
try
{
_app.Update(obj);
}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.InnerException?.Message ?? ex.Message;
}
return result;
}
/// <summary>
/// 加载列表
/// </summary>
[HttpGet]
public TableData Load([FromQuery]Query<%=ModuleName%>ListReq request)
{
return _app.Load(request);
}
/// <summary>
/// 批量删除
/// </summary>
[HttpPost]
public Response Delete([FromBody]string[] ids)
{
var result = new Response();
try
{
_app.Delete(ids);
}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.InnerException?.Message ?? ex.Message;
}
return result;
}
public <%=ModuleName%>sController(<%=ModuleName%>App app)
{
_app = app;
}
}
}

View File

@@ -0,0 +1,66 @@
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="../Internal/Model.cs" %>
<%@ Assembly Src="../Internal/Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="Table"
Type="SchemaExplorer.TableSchema" %>
<%@ Property Name="HeaderModel"
Type="System.Boolean"
Category="1.Database"
Default="true"
Description="是否为启用头表模式,即类似‘入库订单’界面" %>
<%@ Property Name="EntityNamespace"
Type="System.String" %>
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using OpenAuth.Repository.Core;
namespace OpenAuth.App.Request
{
/// <summary>
/// <%= Table.Description %>
/// </summary>
[Table("<%= Table.Name%>")]
public partial class AddOrUpdate<%= Table.Name %>Req
{
<% foreach(ColumnSchema p in Table.Columns) {
%>
/// <summary>
/// <%=p.Description %>
/// </summary>
public <%= p.SystemType.ToNullableType(p.AllowDBNull == true) %> <%= p.Name%> { get; set; }
<% } %>
//todo:添加自己的请求字段
<%
if(Table.Name.Contains("Tbl") && (!Table.Name.Contains("Dtbl")) && this.HeaderModel){
var dtblName = Table.Name.Replace("Tbl","Dtbl"); //明细表的表名
%>
public List<AddOrUpdate<%=dtblName%>Req> <%=dtblName%>Reqs { get; set; }
<% } %>
}
}

View File

@@ -12,6 +12,6 @@ namespace OpenAuth.App.Request
{
public class Query<%=ModuleName%>ListReq : PageReq
{
public string orgId { get; set; }
//todo:添加自己的请求字段
}
}

View File

@@ -1,309 +0,0 @@
<%@ Template Language="C#" TargetLanguage="Text" Debug="True" OutputType="None" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="CodeSmith.CustomProperties" %>
<%@ Assembly Name="Mono.Cecil" Path="..\Common" %>
<%@ Assembly Name="ICSharpCode.NRefactory" Path="..\Common" %>
<%@ Assembly Name="ICSharpCode.NRefactory.CSharp" Path="..\Common" %>
<%@ Assembly Src="Internal\Model.cs" %>
<%@ Assembly Src="Internal\Extensions.cs" %>
<%@ Assembly Src="Internal\Generator.cs" %>
<%@ Assembly Src="Internal\Parser.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="SourceDatabase"
Type="SchemaExplorer.DatabaseSchema"
Category="1.Database"
OnChanged="OnSourceDatabaseChanged"
Description="The source database." %>
<%@ Property Name="ContextNamespace"
Type="System.String"
Category="2.Class"
OnChanged="OnContextNamespaceChanged"
Description="The namespace to use for the data context class files."%>
<%@ Property Name="EntityNamespace"
Type="System.String"
Category="2.Class"
Description="The namespace to use for the entity class files."%>
<%@ Property Name="MappingNamespace"
Type="System.String"
Category="2.Class"
Description="The namespace to use for the mapping class files."%>
<%@ Property Name="ContextDirectory"
Category="3.Output"
Type="System.String"
Default=".\"
Optional="True"
Description="The folder to save the generated context files."
Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
<%@ Property Name="EntityDirectory"
Category="3.Output"
Type="System.String"
Default=".\Entities"
Optional="True"
Description="The folder to save the generated entity files."
Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
<%@ Property Name="MappingDirectory"
Category="3.Output"
Type="System.String"
Default=".\Mapping"
Optional="True"
Description="The folder to save the generated mapping files."
Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
<%@ Property Name="TableNaming"
Type="SchemaMapper.TableNaming"
Category="4.Hints"
Default="Singular"
Description="Provide generator a hint as to how the tables are named." %>
<%@ Property Name="EntityNaming"
Type="SchemaMapper.EntityNaming"
Category="4.Hints"
Default="Singular"
Description="Tell generator how the entities are to be named." %>
<%@ Property Name="RelationshipNaming"
Type="SchemaMapper.RelationshipNaming"
Category="4.Hints"
Default="Plural"
Description="Tell generator how the relationships are to be named." %>
<%@ Property Name="ContextNaming"
Type="SchemaMapper.ContextNaming"
Category="4.Hints"
Default="Plural"
Description="Tell generator how the context properties are to be named." %>
<%@ Property Name="IgnoreList"
Type="CodeSmith.CustomProperties.StringCollection"
Category="5.Customization"
Default="sysdiagrams$"
Optional="True"
Description="List of regular expressions to ignore tables, views and commands when generating mapping." %>
<%@ Property Name="InclusionMode"
Type="Boolean"
Category="5.Customization"
Default="False"
Optional="True"
Description="Change the IgnoreList to be a list of table to include instead of ignore." %>
<%@ Property Name="CleanExpressions"
Type="CodeSmith.CustomProperties.StringCollection"
Category="5.Customization"
Default="^(sp|tbl|udf|vw)_"
Optional="True"
Description="List of regular expressions to clean table, view and column names." %>
<%@ Property Name="InterfaceMode"
Type="Boolean"
Category="5.Customization"
Default="False"
Optional="True"
Description="Use interfaces for DbContext." %>
<%@ Register Name="ContextGeneratedClass"
Template="Internal\Context.Generated.cst"
MergeProperties="False" %>
<%@ Register Name="EntityGeneratedClass"
Template="Internal\Entity.Generated.cst"
MergeProperties="False" %>
<%@ Register Name="MappingGeneratedClass"
Template="Internal\Mapping.Generated.cst"
MergeProperties="False" %>
Generating Entities ...
<% Generate(); %>
<script runat="template">
public void Generate()
{
Stopwatch watch = Stopwatch.StartNew();
string outputDirectory = Path.GetFullPath(ContextDirectory);
if (!Directory.Exists(outputDirectory))
Directory.CreateDirectory(outputDirectory);
if (SourceDatabase != null)
{
this.Progress.MaximumValue = (SourceDatabase.Tables.Count * 3) + 1;
this.Progress.Step = 1;
}
Generator generator = new Generator();
generator.Settings.TableNaming = TableNaming;
generator.Settings.EntityNaming = EntityNaming;
generator.Settings.RelationshipNaming = RelationshipNaming;
generator.Settings.ContextNaming = ContextNaming;
foreach(string s in IgnoreList)
if (!string.IsNullOrEmpty(s))
generator.Settings.IgnoreExpressions.Add(s);
foreach(string s in CleanExpressions)
if (!string.IsNullOrEmpty(s))
generator.Settings.CleanExpressions.Add(s);
generator.SchemaItemProcessed += OnSchemaItemProcessed;
// generate from database
EntityContext context = generator.Generate(SourceDatabase);
// update model from source files
Synchronizer.UpdateFromSource(context, ContextDirectory, MappingDirectory);
CreateContextClass(context);
CreateMappingClasses(context);
CreateEntityClasses(context);
this.RegisterReference("System.Configuration");
this.RegisterReference("System.Data");
this.RegisterReference("System.Data.Entity");
this.RegisterReference("System.Runtime.Serialization");
this.RegisterReference("EntityFramework");
watch.Stop();
Response.WriteLine("Generate Time: " + watch.ElapsedMilliseconds + " ms");
}
public void CreateContextClass(EntityContext entityContext)
{
ContextGeneratedClass generatedClass = this.Create<ContextGeneratedClass>();
this.CopyPropertiesTo(generatedClass);
string rootDirectory = Path.GetFullPath(ContextDirectory);
string className = entityContext.ClassName;
string generatedFile = className + ".cs";
generatedFile = Path.Combine(rootDirectory, generatedFile);
generatedClass.EntityContext = entityContext;
Response.WriteLine(generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true);
}
public void CreateMappingClasses(EntityContext entityContext)
{
MappingGeneratedClass generatedClass = this.Create<MappingGeneratedClass>();
this.CopyPropertiesTo(generatedClass);
foreach(Entity entity in entityContext.Entities)
{
Stopwatch watch = Stopwatch.StartNew();
Debug.WriteLine(string.Format(
"Creating Mapping Class '{0}' ...",
entity.ClassName));
string rootDirectory = Path.GetFullPath(MappingDirectory);
CreateMapping(generatedClass, entity, rootDirectory);
Debug.WriteLine(string.Format(
"Created Mapping Class '{0}' in {1} ms.",
entity.ClassName,
watch.Elapsed.TotalMilliseconds.ToString()));
this.Progress.PerformStep();
}
}
public void CreateMapping(MappingGeneratedClass generatedClass, Entity entity, string rootDirectory)
{
string className = entity.MappingName;
string generatedFile = className + ".cs";
generatedFile = Path.Combine(rootDirectory, generatedFile);
generatedClass.Entity = entity;
Response.WriteLine(generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true);
}
public void CreateEntityClasses(EntityContext entityContext)
{
EntityGeneratedClass generatedClass = this.Create<EntityGeneratedClass>();
this.CopyPropertiesTo(generatedClass);
foreach(Entity entity in entityContext.Entities)
{
Stopwatch watch = Stopwatch.StartNew();
Debug.WriteLine(string.Format(
"Creating Entity Class '{0}' ...",
entity.ClassName));
string rootDirectory = Path.GetFullPath(EntityDirectory);
CreateEntity(generatedClass, entity, rootDirectory);
Debug.WriteLine(string.Format(
"Created Entity Class '{0}' in {1} ms.",
entity.ClassName,
watch.Elapsed.TotalMilliseconds.ToString()));
this.Progress.PerformStep();
}
}
public void CreateEntity(EntityGeneratedClass generatedClass, Entity entity, string rootDirectory)
{
string className = entity.ClassName;
string generatedFile = className + ".cs";
generatedFile = Path.Combine(rootDirectory, generatedFile);
generatedClass.Entity = entity;
Response.WriteLine(generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true);
}
private void OnSchemaItemProcessed(object sender, SchemaItemProcessedEventArgs e)
{
this.Progress.PerformStep();
Response.WriteLine(e.Name);
}
private void OnSourceDatabaseChanged(object sender, EventArgs e)
{
if (SourceDatabase == null)
return;
string name = StringUtil.ToPascalCase(SourceDatabase.Database.Name);
if (string.IsNullOrEmpty(ContextNamespace))
ContextNamespace = name + ".Data";
}
private void OnContextNamespaceChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(ContextNamespace))
return;
if (string.IsNullOrEmpty(EntityNamespace))
EntityNamespace = ContextNamespace + ".Entities";
if (string.IsNullOrEmpty(MappingNamespace))
MappingNamespace = ContextNamespace + ".Mapping";
}
</script>

View File

@@ -1,7 +1,7 @@
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %>
<%@ Assembly Src="../Internal/Model.cs" %>
<%@ Assembly Src="../Internal/Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
@@ -10,87 +10,72 @@
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="EntityContext" Type="SchemaMapper.EntityContext" %>
<%@ Property Name="WholeDb"
Type="System.Boolean"
Category="1.Database"
Default="true"
Description="是否为整个数据库" %>
<%@ Property Name="SourceDatabase"
Type="SchemaExplorer.DatabaseSchema"
Category="1.Database"
Description="The source database." %>
<%@ Property Name="SourceTables"
Type="SchemaExplorer.TableSchemaCollection"
Category="1.Database" Description="选择部分表" %>
<%@ Property Name="ContextNamespace" Type="System.String" %>
<%@ Property Name="EntityNamespace" Type="System.String" %>
<%@ Property Name="MappingNamespace" Type="System.String" %>
<%@ Property Name="InterfaceMode" Type="Boolean" Default="False" Optional="True" %>
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Data.Entity;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using <%= EntityNamespace %>;
using <%= MappingNamespace %>;
namespace <%= ContextNamespace %>
{
<% if (InterfaceMode) { %>
public interface IDbContext : IDisposable
{
System.Data.Entity.Database Database { get; }
System.Data.Entity.Infrastructure.DbChangeTracker ChangeTracker { get; }
System.Data.Entity.Infrastructure.DbContextConfiguration Configuration { get; }
System.Data.Entity.Infrastructure.DbEntityEntry Entry(object entity);
System.Data.Entity.Infrastructure.DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
IEnumerable<System.Data.Entity.Validation.DbEntityValidationResult> GetValidationErrors();
System.Data.Entity.DbSet Set(Type entityType);
System.Data.Entity.IDbSet<TEntity> Set<TEntity>() where TEntity : class;
int SaveChanges();
}
public partial interface I<%= EntityContext.ClassName.ToSafeName() %> : IDbContext
{
<% foreach(var p in EntityContext.Entities) { %>
System.Data.Entity.IDbSet<<%= EntityNamespace %>.<%= p.ClassName.ToSafeName() %>> <%= p.ContextName.ToSafeName() %> { get; set; }
<% } // foreach %>
}
<% } // if interface %>
public partial class <%= EntityContext.ClassName.ToSafeName() %>: DbContext<%= InterfaceMode ? ", I" + EntityContext.ClassName.ToSafeName() : string.Empty %>
{
static <%= EntityContext.ClassName.ToSafeName() %>()
{
Database.SetInitializer< <%= EntityContext.ClassName.ToSafeName() %>>(null);
<%
string dbContextName;
if(WholeDb){
dbContextName = SourceDatabase.Name.ToSafeName();
}
public <%= EntityContext.ClassName.ToSafeName() %>()
:base("Name=<%= EntityContext.ClassName.ToSafeName() %>")
{ }
public <%= EntityContext.ClassName.ToSafeName() %>(string nameOrConnectionString)
: base(nameOrConnectionString)
{ }
<% foreach(var p in EntityContext.Entities) { %>
public System.Data.Entity.<%= InterfaceMode ? "I" : "" %>DbSet<<%= p.ClassName.ToSafeName() %>> <%= p.ContextName.ToSafeName() %> { get; set; }
<% } // foreach %>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
else{
dbContextName = SourceTables.First().Database.Name.ToSafeName();
}
dbContextName = StringUtil.ToPascalCase(dbContextName);
Response.WriteLine(" public partial class "+ dbContextName +"Context: DbContext");
%>
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
<% foreach(var p in EntityContext.Entities) { %>
modelBuilder.Configurations.Add(new <%= p.MappingName.ToSafeName() %>());
<% } // foreach %>
//当主键为联合主键时,需要把这里的内容拷贝到对应的位置
<%
TableSchemaCollection tables;
if(WholeDb){
tables = SourceDatabase.Tables;
}
else{
tables = SourceTables;
}
// InitializeMapping(modelBuilder);
foreach(TableSchema table in tables)
{
if(table.PrimaryKeys.Count <=1) continue;
var keys = string.Join(",", table.Columns.Where(u=>u.IsPrimaryKeyMember==true)
.Select(u =>"c."+u.Name));
Response.WriteLine(" modelBuilder.Entity<"+table.Name+">()");
Response.WriteLine(" .HasKey(c => new { "+keys+" });");
}
%>
}
<% if (InterfaceMode) { %>
System.Data.Entity.IDbSet<TEntity> IDbContext.Set<TEntity>()
<%
foreach(TableSchema table in tables)
{
return base.Set<TEntity>();
Response.WriteLine(" public virtual DbSet<"+table.Name+"> "+StringUtil.ToPascalCase(StringUtil.ToPlural(table.Name))+" { get; set; }");
}
<% } // if interface %>
%>
}
}

View File

@@ -1,7 +1,7 @@
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %>
<%@ Assembly Src="../Internal/Model.cs" %>
<%@ Assembly Src="../Internal/Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
@@ -10,8 +10,8 @@
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="Entity"
Type="SchemaMapper.Entity" %>
<%@ Property Name="Table"
Type="SchemaExplorer.TableSchema" %>
<%@ Property Name="EntityNamespace"
Type="System.String" %>
@@ -26,47 +26,50 @@
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using OpenAuth.Repository.Core;
namespace <%= EntityNamespace %>
{
/// <summary>
/// <%= Entity.Description %>
/// <%= Table.Description %>
/// </summary>
public partial class <%= Entity.ClassName.ToSafeName() %> : Entity
[Table("<%= Table.Name%>")]
public partial class <%= Table.Name %> : Entity
{
public <%= Entity.ClassName.ToSafeName() %>()
public <%= Table.Name %>()
{
<% foreach(var p in Entity.Properties) {
if(p.IsPrimaryKey ==true) continue;
string type = p.SystemType.ToNullableType(p.IsNullable == true);
if(type =="int" || type=="decimal")
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= 0;");
else if(type =="string")
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= string.Empty;");
else if(type.ToLower().Contains("datetime"))
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= DateTime.Now;");
} // foreach %>
<% foreach(var r in Entity.Relationships.Where(e => e.ThisCardinality == Cardinality.Many)) { %>
<%= r.ThisPropertyName.ToSafeName() %> = new List<<%= r.OtherEntity.ToSafeName() %>>();
<% } // foreach %>
<% foreach(ColumnSchema p in Table.Columns) {
if(p.IsPrimaryKeyMember) continue;
string type = p.SystemType.ToNullableType(p.AllowDBNull == true);
if(type =="int" || type=="decimal")
Response.WriteLine(" this."+p.Name+"= 0;");
else if(type =="string")
Response.WriteLine(" this."+p.Name+"= string.Empty;");
else if(type.ToLower().Contains("datetime"))
Response.WriteLine(" this."+p.Name+"= DateTime.Now;");
} // foreach %>
}
<% foreach(var p in Entity.Properties) {
if(p.IsPrimaryKey ==true) continue;
%>
<%
foreach(ColumnSchema p in Table.Columns) {
if(p.IsPrimaryKeyMember) continue;
%>
/// <summary>
/// <%=p.Description %>
/// </summary>
public <%= p.SystemType.ToNullableType(p.IsNullable == true) %> <%= p.PropertyName.ToSafeName() %> { get; set; }
<% } // foreach %>
<% foreach(var r in Entity.Relationships) { %>
<% if(r.ThisCardinality == Cardinality.Many) { %>
public virtual ICollection<<%= r.OtherEntity.ToSafeName() %>> <%= r.ThisPropertyName.ToSafeName() %> { get; set; }
<% } else { %>
public virtual <%= r.OtherEntity.ToSafeName() %> <%= r.ThisPropertyName.ToSafeName() %> { get; set; }
<% } %>
<% } // foreach %>
/// <%=p.Description %>
/// </summary>
[Description("<%=p.Description%>")]
<%if(p.Name.LastIndexOf("Id") != -1){%>
[Browsable(false)]
<%}%>
<%if(p.DataType == DbType.Byte){%>
public bool <%= p.Name%> { get; set; }
<%}else{%>
public <%= p.SystemType.ToNullableType(p.AllowDBNull == true) %> <%= p.Name%> { get; set; }
<%}%>
<% } // foreach %>
}
}

View File

@@ -205,6 +205,27 @@ namespace SchemaMapper
get { return _settings; }
}
//按表信息创建DbContext
public EntityContext Generate(TableSchema tableSchema)
{
// only DeepLoad when in ignore mode
tableSchema.DeepLoad = !Settings.InclusionMode;
var entityContext = new EntityContext();
entityContext.DatabaseName = tableSchema.Database.Name;
string dataContextName = StringUtil.ToPascalCase(tableSchema.Database.Name) + "Context";
dataContextName = _namer.UniqueClassName(dataContextName);
entityContext.ClassName = dataContextName;
GetEntity(entityContext, tableSchema);
return entityContext;
}
//按数据库连接信息创建DbContext
public EntityContext Generate(DatabaseSchema databaseSchema)
{
// only DeepLoad when in ignore mode
@@ -240,8 +261,8 @@ namespace SchemaMapper
return entityContext;
}
private Entity GetEntity(EntityContext entityContext, TableSchema tableSchema, bool processRelationships = true, bool processMethods = true)
//根据DbContext和tableSchema获取实体
public Entity GetEntity(EntityContext entityContext, TableSchema tableSchema, bool processRelationships = true, bool processMethods = true)
{
string key = tableSchema.FullName;
@@ -363,7 +384,7 @@ namespace SchemaMapper
if (Settings.IsIgnored(tableKey.ForeignKeyTable.FullName)
|| Settings.IsIgnored(tableKey.PrimaryKeyTable.FullName))
{
Debug.WriteLine("Skipping relationship '{0}' because table '{1}' or '{2}' is ignored.",
Debug.WriteLine("Skipping relationship '{0}' because table '{1}' or '{2}' is ignored.",
tableKey.FullName, tableKey.ForeignKeyTable.FullName, tableKey.PrimaryKeyTable.FullName);
continue;

View File

@@ -1,294 +0,0 @@
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="Entity" Type="SchemaMapper.Entity" %>
<%@ Property Name="ContextNamespace" Type="System.String" %>
<%@ Property Name="EntityNamespace" Type="System.String" %>
<%@ Property Name="MappingNamespace" Type="System.String" %>
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace <%= MappingNamespace %>
{
public partial class <%= Entity.MappingName.ToSafeName() %>
: System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<<%= EntityNamespace %>.<%= Entity.ClassName.ToSafeName() %>>
{
public <%= Entity.MappingName.ToSafeName() %>()
{
// table
<% if (string.IsNullOrEmpty(Entity.TableSchema)) { %>
ToTable("<%= Entity.TableName %>");
<% } else { %>
ToTable("<%= Entity.TableName %>", "<%= Entity.TableSchema %>");
<% } %>
// keys
<% if (Entity.Properties.PrimaryKeys.Count() > 0) { %>
HasKey(t => <%= KeyExpression(Entity.Properties.PrimaryKeys, "t") %>);
<% } %>
// Properties
<%
foreach(var p in Entity.Properties)
{
Response.Write(PropertyExpression(p));
}
%>
// Relationships
<%
foreach(var r in Entity.Relationships.Where(e => e.IsMapped))
{
if (r.IsManyToMany)
Response.Write(ManyToManyExpression(r));
else
Response.Write(RelationshipExpression(r));
}
%>
}
}
}
<script runat="template">
public string PropertyExpression(Property property)
{
bool isString = property.SystemType == typeof(string);
bool isByteArray = property.SystemType == typeof(byte[]);
bool isDecimal = property.SystemType == typeof(Decimal);
StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4);
sb.Append("Property(t => t.");
sb.Append(property.PropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasColumnName(\"");
sb.Append(property.ColumnName);
sb.Append("\")");
if (property.IsIdentity == true)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)");
}
else if (property.IsAutoGenerated == true)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)");
}
if ((isString || isByteArray) && (property.MaxLength > 0 && property.MaxLength < 8000))
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasMaxLength(");
sb.Append(property.MaxLength);
sb.Append(")");
}
if (isDecimal && property.Precision.HasValue && property.Scale.HasValue)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasPrecision(");
sb.Append(property.Precision);
sb.Append(", ");
sb.Append(property.Scale);
sb.Append(")");
}
if (property.IsRowVersion == true && isByteArray)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".IsRowVersion()");
}
sb.AppendLine();
sb.Append(' ', 4 * 4);
if (property.IsRequired == true)
sb.Append(".IsRequired()");
else
sb.Append(".IsOptional()");
sb.AppendLine(";");
return sb.ToString();
}
public string ManyToManyExpression(Relationship relationship)
{
StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4);
sb.Append("HasMany(t => t.");
sb.Append(relationship.ThisPropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WithMany(t => t.");
sb.Append(relationship.OtherPropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".Map(m =>");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append("{");
sb.AppendLine();
sb.Append(' ', 5 * 4);
sb.Append("m.ToTable(\"");
sb.Append(relationship.JoinTable);
sb.Append("\", \"");
sb.Append(relationship.JoinSchema);
sb.Append("\");");
sb.AppendLine();
sb.Append(' ', 5 * 4);
sb.Append("m.MapLeftKey(");
sb.Append(relationship.JoinThisColumn.ToDelimitedString(", ", "\"{0}\""));
sb.Append(");");
sb.AppendLine();
sb.Append(' ', 5 * 4);
sb.Append("m.MapRightKey(");
sb.Append(relationship.JoinOtherColumn.ToDelimitedString(", ", "\"{0}\""));
sb.Append(");");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append("})");
sb.Append(";");
sb.AppendLine();
return sb.ToString();
}
public string RelationshipExpression(Relationship relationship)
{
StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4);
if (relationship.ThisCardinality == Cardinality.One)
{
sb.Append("HasRequired(t => t.");
sb.Append(relationship.ThisPropertyName);
sb.Append(")");
}
else if (relationship.ThisCardinality == Cardinality.ZeroOrOne)
{
sb.Append("HasOptional(t => t.");
sb.Append(relationship.ThisPropertyName);
sb.Append(")");
}
if (relationship.OtherCardinality == Cardinality.Many)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WithMany(t => t.");
sb.Append(relationship.OtherPropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasForeignKey(d => ");
sb.Append(KeyExpression(relationship.ThisProperties, "d"));
sb.Append(")");
}
else
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WithOptional(t => t.");
sb.Append(relationship.OtherPropertyName);
sb.Append(")");
}
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WillCascadeOnDelete(");
sb.Append(relationship.CascadeDelete == true ? "true" : "false");
sb.Append(")");
sb.AppendLine(";");
return sb.ToString();
}
public string KeyExpression(IEnumerable<Property> keys, string alias = "t")
{
StringBuilder sb = new StringBuilder();
if (keys.Count() == 1)
{
sb.Append(alias);
sb.Append(".");
sb.Append(keys.FirstOrDefault().PropertyName);
}
else
{
sb.Append("new { ");
foreach(var p in keys)
{
if (sb.Length > 6)
sb.Append(", ");
sb.Append(alias);
sb.Append(".");
sb.Append(p.PropertyName);
}
sb.Append(" }");
}
return sb.ToString();
}
public string KeyExpression(IEnumerable<string> keys, string alias = "t")
{
StringBuilder sb = new StringBuilder();
if (keys.Count() == 1)
{
sb.Append(alias);
sb.Append(".");
sb.Append(keys.FirstOrDefault());
}
else
{
sb.Append("new { ");
foreach(var p in keys)
{
if (sb.Length > 6)
sb.Append(", ");
sb.Append(alias);
sb.Append(".");
sb.Append(p);
}
sb.Append(" }");
}
return sb.ToString();
}
</script>

View File

@@ -1,53 +0,0 @@
<%--
Name: Database Table Properties
Author: yubaolee
Description: Create a list of properties from a database table
--%>
<%@ CodeTemplate Language="C#" Encoding="utf-8" TargetLanguage="C#" Debug="False" Description="应用层" %>
<%@ Property Name="ModuleName" Type="String" Category="Context" Description="模块名称" %>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
using System;
using System.Collections.Generic;
using System.Linq;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.App.SSO;
using OpenAuth.Repository.Domain;
namespace OpenAuth.App
{
public class <%=ModuleName%>App : BaseApp<<%=ModuleName%>>
{
public RevelanceManagerApp ReleManagerApp { get; set; }
/// <summary>
/// 加载列表
/// </summary>
public TableData Load(Query<%=ModuleName%>ListReq request)
{
return new TableData
{
count = Repository.GetCount(null),
data = Repository.Find(request.page, request.limit, "Id desc")
};
}
public void Add(<%=ModuleName%> obj)
{
Repository.Add(obj);
}
public void Update(<%=ModuleName%> obj)
{
UnitWork.Update<<%=ModuleName%>>(u => u.Id == obj.Id, u => new <%=ModuleName%>
{
//todo:要修改的字段赋值
});
}
}
}

View File

@@ -10,34 +10,39 @@ Description: Create a list of properties from a database table
<%@ Import Namespace="SchemaExplorer" %>
using System;
using System.Web.Http;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Linq;
using Infrastructure;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Mvc.Models;
using OpenAuth.Repository.Domain;
namespace OpenAuth.Mvc.Controllers
{
public class <%=ModuleName%>sController : BaseController
{
public <%=ModuleName%>App App { get; set; }
private readonly <%=ModuleName%>App _app;
//
[Authenticate]
public <%=ModuleName%>sController(<%=ModuleName%>App app, IAuth auth) : base(auth)
{
_app = app;
}
//主页
public ActionResult Index()
{
return View();
}
//添加或修改
[System.Web.Mvc.HttpPost]
[HttpPost]
public string Add(<%=ModuleName%> obj)
{
try
{
App.Add(obj);
_app.Add(obj);
}
catch (Exception ex)
@@ -49,12 +54,12 @@ namespace OpenAuth.Mvc.Controllers
}
//添加或修改
[System.Web.Mvc.HttpPost]
[HttpPost]
public string Update(<%=ModuleName%> obj)
{
try
{
App.Update(obj);
_app.Update(obj);
}
catch (Exception ex)
@@ -68,17 +73,17 @@ namespace OpenAuth.Mvc.Controllers
/// <summary>
/// 加载列表
/// </summary>
public string Load([FromUri]Query<%=ModuleName%>ListReq request)
public string Load([FromQuery]Query<%=ModuleName%>ListReq request)
{
return JsonHelper.Instance.Serialize(App.Load(request));
return JsonHelper.Instance.Serialize(_app.Load(request));
}
[System.Web.Mvc.HttpPost]
[HttpPost]
public string Delete(string[] ids)
{
try
{
App.Delete(ids);
_app.Delete(ids);
}
catch (Exception e)
{

View File

@@ -21,45 +21,34 @@ Description="连接的数据库" %>
<blockquote class="layui-elem-quote news_search toolList" id="menus">
</blockquote>
<div class="layui-row">
<div class="layui-col-xs2">
<ul id="tree" class="ztree"
style="padding: 2px; border: 1px solid #ddd; overflow: auto;">
</ul>
</div>
<div class="layui-col-xs10">
<table class="layui-table"
lay-data="{height: 'full-80', page:true, id:'mainList'}"
lay-filter="list" lay-size="sm">
<thead>
<tr>
<th lay-data="{checkbox:true, fixed: true}"></th>
<% foreach (ColumnSchema column in this.SourceTable.Columns) {%>
<th lay-data="{field:'<%=column.Name%>', width:150}"><%=Tools.GetDescription(column)%></th>
<% }%>
<th lay-data="{fixed: 'right', width:160, align:'center', toolbar: '#barList'}"></th>
</tr>
</thead>
</table>
</div>
</div>
<div class="layui-card">
<script type="text/html" id="barList">
<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
</script>
<table class="layui-table" id="mainList"
lay-data="{height: 'full-80', page:true, id:'mainList'}"
lay-filter="list" lay-size="sm">
</table>
<script type="text/html" id="Disable">
{{# if(d.Disable){ }}
<span class="layui-badge">已禁用</span>
{{# } else{}}
<span class="layui-badge layui-bg-green">正常</span>
{{# } }}
</script>
</div>
<!--添加/编辑窗口-->
<div id="divEdit" style="display: none">
<form class="layui-form" action="" id="formEdit">
<% foreach (ColumnSchema column in this.SourceTable.Columns) {
if(column.IsPrimaryKeyMember){%>
<input type="hidden" name="<%=column.Name%>" v-model="<%=column.Name%>" />
<input type="hidden" name="<%=column.Name%>" v-model="tmp.<%=column.Name%>" />
<%}else if(CSharpAlias[column.SystemType.FullName] == "bool") {%>
<div class="layui-form-item">
<label class="layui-form-label"><%=Tools.GetDescription(column)%></label>
<div class="layui-input-block">
<input type="checkbox" name="<%=column.Name%>" v-model="<%=column.Name%>" lay-skin="switch" value="1">
<input type="checkbox" name="<%=column.Name%>" v-model="tmp.<%=column.Name%>" lay-skin="switch" value="1">
</div>
</div>
<%}else if(CSharpAlias[column.SystemType.FullName] == "int" ) {%>
@@ -74,7 +63,7 @@ Description="连接的数据库" %>
<div class="layui-form-item">
<label class="layui-form-label"><%=Tools.GetDescription(column)%></label>
<div class="layui-input-block">
<input type="text" name="<%=column.Name%>" v-model="<%=column.Name%>" required lay-verify="required"
<input type="text" name="<%=column.Name%>" v-model="tmp.<%=column.Name%>" required lay-verify="required"
placeholder="<%=Tools.GetDescription(column)%>" autocomplete="off" class="layui-input">
</div>
</div>
@@ -104,6 +93,6 @@ Description="连接的数据库" %>
</div>
<script type="text/javascript" src="/layui/layui.js"></script>
<script type="text/javascript" src="/userJs/<%=ModuleName%>s.js"></script>
<script type="text/javascript" src="/userJs/<%=ModuleName.ToLower()%>s.js"></script>

View File

@@ -13,73 +13,63 @@ Author: yubaolee
layui.config({
base: "/js/"
}).use(['form','vue', 'ztree', 'layer', 'jquery', 'table','droptree','openauth', 'utils'], function () {
}).use(['form', 'vue', 'ztree', 'layer', 'jquery', 'table', 'droptree', 'openauth', 'utils'], function () {
var form = layui.form,
layer = layui.layer,
$ = layui.jquery;
var table = layui.table;
var openauth = layui.openauth;
var toplayer = (top == undefined || top.layer === undefined) ? layer : top.layer; //顶层的LAYER
layui.droptree("/UserSession/GetOrgs", "#Organizations", "#OrganizationIds");
$("#menus").loadMenus("<%=ModuleName%>");
//加载表头
$.getJSON('/<%=ModuleName%>s/Load',
{ page: 1, limit: 1 },
function (data) {
var columns = data.columnHeaders.map(function (e) {
return {
field: e.Key,
title: e.Description
};
});
columns.unshift({
type: 'checkbox',
fixed: 'left'
});
table.render({
elem: '#mainList',
page: true,
url: '/<%=ModuleName%>s/Load',
cols: [columns]
, response: {
statusCode: 200 //规定成功的状态码默认0
}
});
});
//主列表加载,可反复调用进行刷新
var config= {}; //table的参数如搜索key点击tree的id
var mainList = function (options) {
var config = {}; //table的参数如搜索key点击tree的id
var mainList = function(options) {
if (options != undefined) {
$.extend(config, options);
}
table.reload('mainList', {
url: '/<%=ModuleName%>s/Load',
where: config
});
}
//左边树状机构列表
var ztree = function () {
var url = '/UserSession/GetOrgs';
var zTreeObj;
var setting = {
view: { selectedMulti: false },
data: {
key: {
name: 'Name',
title: 'Name'
},
simpleData: {
enable: true,
idKey: 'Id',
pIdKey: 'ParentId',
rootPId: 'null'
}
},
callback: {
onClick: function (event, treeId, treeNode) {
mainList({ orgId: treeNode.Id });
}
}
};
var load = function () {
$.getJSON(url, function (json) {
zTreeObj = $.fn.zTree.init($("#tree"), setting);
var newNode = { Name: "根节点", Id: null, ParentId: "" };
json.push(newNode);
zTreeObj.addNodes(null, json);
mainList({ orgId: "" });
zTreeObj.expandAll(true);
table.reload('mainList',
{
url: '/<%=ModuleName%>s/Load',
where: config
, response: {
statusCode: 200 //规定成功的状态码默认0
}
});
};
load();
return {
reload: load
}
}();
};
mainList();
//添加(编辑)对话框
var editDlg = function() {
var vm = new Vue({
el: "#formEdit"
});
var editDlg = function () {
var vm;
var update = false; //是否为更新
var show = function (data) {
var title = update ? "编辑信息" : "添加";
@@ -88,21 +78,46 @@ layui.config({
area: ["500px", "400px"],
type: 1,
content: $('#divEdit'),
success: function() {
vm.$set('$data', data);
success: function () {
if(vm == undefined){
vm = new Vue({
el: "#formEdit",
data(){
return {
tmp:data //使用一个tmp封装一下后面可以直接用vm.tmp赋值
}
},
watch:{
tmp(val){
this.$nextTick(function () {
form.render(); //刷新select等
layui.droptree("/Applications/GetList", "#AppName", "#AppId", false);
})
}
},
mounted(){
form.render();
layui.droptree("/Applications/GetList", "#AppName", "#AppId", false);
}
});
}else{
vm.tmp = Object.assign({}, vm.tmp,data)
}
},
end: mainList
});
var url = "/<%=ModuleName%>s/Add";
if (update) {
url = "/<%=ModuleName%>s/Update";
url = "/<%=ModuleName%>s/Update";
}
//提交数据
form.on('submit(formSubmit)',
function(data) {
function (data) {
$.post(url,
data.field,
function(data) {
function (data) {
layer.msg(data.Message);
},
"json");
@@ -110,25 +125,25 @@ layui.config({
});
}
return {
add: function() { //弹出添加
add: function () { //弹出添加
update = false;
show({
Id: ''
});
},
update: function(data) { //弹出编辑框
update: function (data) { //弹出编辑框
update = true;
show(data);
}
};
}();
//监听表格内部按钮
table.on('tool(list)', function (obj) {
var data = obj.data;
if (obj.event === 'detail') { //查看
layer.msg('ID' + data.Id + ' 的查看操作');
}
}
});
@@ -144,20 +159,20 @@ layui.config({
, btnAdd: function () { //添加
editDlg.add();
}
, btnEdit: function () { //编辑
var checkStatus = table.checkStatus('mainList')
, data = checkStatus.data;
if (data.length != 1) {
layer.msg("请选择编辑的行,且同时只能编辑一行");
return;
}
editDlg.update(data[0]);
}
, btnEdit: function () { //编辑
var checkStatus = table.checkStatus('mainList')
, data = checkStatus.data;
if (data.length != 1) {
layer.msg("请选择编辑的行,且同时只能编辑一行");
return;
}
editDlg.update(data[0]);
}
, search: function () { //搜索
mainList({ key: $('#key').val() });
}
, btnRefresh: function() {
, btnRefresh: function () {
mainList();
}
};
@@ -168,4 +183,4 @@ layui.config({
});
//监听页面主按钮操作 end
})
})

View File

@@ -1,4 +1,8 @@
<%@ Template Language="C#" TargetLanguage="Text" Debug="True" OutputType="None" %>
<%--
Author: yubaolee
Description: 用于生成OpenAuth.Core开源版前端Web界面包括mvc controller/csthml/js
--%>
<%@ Template Language="C#" TargetLanguage="Text" Debug="True" OutputType="None" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="CodeSmith.CustomProperties" %>
@@ -36,12 +40,6 @@ OnChanged="OnSourceDatabaseChanged"%>
Description="代码生成路径"
Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
<%@ Register Name="ApplicationGenerateClass"
Template="Web\Application.cst"
MergeProperties="False" %>
<%@ Register Name="RequestGenerateClass"
Template="Web\Request.cst"
MergeProperties="False" %>
<%@ Register Name="HtmlGenerateClass"
Template="Web\Index.cshtml.cst"
MergeProperties="False" %>
@@ -61,8 +59,6 @@ Generating Entities ...
string outputDirectory = Path.GetFullPath(directory);
CreateControllerClass();
CreateApplicationClass();
CreateReqClass();
CreateHtmlClass();
CreateJSClass();
@@ -84,23 +80,7 @@ Generating Entities ...
string rootDirectory = Path.GetFullPath(directory);
string generatedFile = Path.GetFullPath(directory) + "/controllers/"+ ModuleName + "sController.cs";
generatedClass.ModuleName = ModuleName;
Response.WriteLine(generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true);
}
//创建APP层,如UserManagerApp.cs
public void CreateApplicationClass()
{
ApplicationGenerateClass generatedClass = this.Create<ApplicationGenerateClass>();
this.CopyPropertiesTo(generatedClass);
string rootDirectory = Path.GetFullPath(directory);
string generatedFile = Path.GetFullPath(directory) + "/APP/"+ ModuleName + "App.cs";
string generatedFile = Path.GetFullPath(directory) + "/Controllers/"+ ModuleName + "sController.cs";
generatedClass.ModuleName = ModuleName;
@@ -108,22 +88,6 @@ Generating Entities ...
generatedClass.RenderToFile(generatedFile, generatedFile, true);
}
//创建请求参数,如QueryUserListReq.cs
public void CreateReqClass()
{
RequestGenerateClass generatedClass = this.Create<RequestGenerateClass>();
this.CopyPropertiesTo(generatedClass);
string rootDirectory = Path.GetFullPath(directory);
string generatedFile = Path.GetFullPath(directory) + "/APP/Request/Query"+ ModuleName + "ListReq.cs";
generatedClass.ModuleName = ModuleName;
Response.WriteLine(generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true);
}
//创建视图,如views/Users/index.html
public void CreateHtmlClass()
@@ -131,7 +95,7 @@ Generating Entities ...
HtmlGenerateClass generatedClass = this.Create<HtmlGenerateClass>();
this.CopyPropertiesTo(generatedClass);
string generatedFile = Path.GetFullPath(directory) + "/views/"+ModuleName+"s/index.cshtml";
string generatedFile = Path.GetFullPath(directory) + "/Views/"+ModuleName+"s/index.cshtml";
generatedClass.ModuleName = ModuleName;
generatedClass.SourceTable = SourceTable;
@@ -158,7 +122,7 @@ Generating Entities ...
//更换数据源时改变ModuleName
private void OnSourceDatabaseChanged(object sender, EventArgs e)
{
if (SourceTable == null || ModuleName != null)
if (SourceTable == null)
return;
ModuleName = SourceTable.Name;
}