!13 优化生成实体,在生成实体后自动在OpenAuthDBContext中新增DbSet

fix issue #I3BUF5
This commit is contained in:
yubaolee 2021-03-21 10:44:46 +08:00
parent fc00492531
commit f164566d2d
7 changed files with 229 additions and 51 deletions

View File

@ -1,8 +1,10 @@
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions;
using Infrastructure.Extensions; using Infrastructure.Extensions;
namespace Infrastructure.Helpers namespace Infrastructure.Helpers
@ -335,5 +337,70 @@ namespace Infrastructure.Helpers
return str; return str;
} }
/// <summary>
/// 括号匹配算法
/// </summary>
/// <param name="dataStr">原始字符串</param>
/// <param name="leftCode">左匹配符号</param>
/// <param name="rightCode">右匹配符号</param>
/// <returns></returns>
private static string parenthesisMatch(string dataStr, char leftCode, char rightCode)
{
Stack stack = new Stack();
string cut_text = "";
for (int i = 0; i < dataStr.Length; ++i)
{
char ch = dataStr[i];
if (stack.Count > 0)
{
cut_text += ch;
}
if (ch == leftCode)
{
stack.Push(ch);
}
if (ch == rightCode)
{
stack.Pop();
if (0 == stack.Count)
{
return cut_text.Substring(0, cut_text.Length - 1);
}
}
}
return "";
}
/// <summary>
/// 替换内容(正则 + 括号匹配算法)
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="addStr">追加内容</param>
public static void RegxAddContentByParenthesis(string path, string addStr)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string originStr = sr.ReadToEnd();
string pattern = @"DbContext\s*?({.*)";
if (Regex.IsMatch(originStr, pattern))
{
Match match = Regex.Match(originStr, pattern, RegexOptions.Singleline);
string cut_str = parenthesisMatch(match.Groups[1].Value, '{', '}'); // 剪切内容(原内容)
string new_str = cut_str + "\r\n " + addStr + "\r\n"; // 实际更新内容
originStr = originStr.Replace(cut_str, new_str);
}
sr.Close();
fs.Close();
FileStream fs2 = new FileStream(path, FileMode.Open, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs2);
sw.WriteLine(originStr);
sw.Close();
fs2.Close();
}
} }
} }

View File

@ -429,6 +429,9 @@ namespace OpenAuth.App
mapPath + mapPath +
$"\\OpenAuth.Repository\\Domain\\", tableInfo.ClassName + ".cs", $"\\OpenAuth.Repository\\Domain\\", tableInfo.ClassName + ".cs",
domainContent); domainContent);
string openAuthDBContextPath = mapPath + "\\OpenAuth.Repository\\OpenAuthDBContext.cs";
FileHelper.RegxAddContentByParenthesis(openAuthDBContextPath, "public virtual DbSet<" + tableInfo.ClassName + "> " + tableInfo.TableName + "s { get; set; }");
} }
private bool IsMysql() private bool IsMysql()

View File

@ -3,9 +3,13 @@ using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
using System.Linq; using System.Linq;
using Autofac.Extensions.DependencyInjection;
using Infrastructure; using Infrastructure;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using OpenAuth.Repository; using OpenAuth.Repository;
using OpenAuth.Repository.Domain; using OpenAuth.Repository.Domain;
@ -15,14 +19,14 @@ namespace OpenAuth.App
{ {
public class DbExtension public class DbExtension
{ {
private OpenAuthDBContext _context; private List<DbContext> _contexts = new List<DbContext>();
private IOptions<AppSetting> _appConfiguration; private IOptions<AppSetting> _appConfiguration;
public DbExtension(OpenAuthDBContext context, IOptions<AppSetting> appConfiguration) public DbExtension(IOptions<AppSetting> appConfiguration, OpenAuthDBContext openAuthDbContext)
{ {
_context = context;
_appConfiguration = appConfiguration; _appConfiguration = appConfiguration;
_contexts.Add(openAuthDbContext); //如果有多个DBContext可以按OpenAuthDBContext同样的方式添加到_contexts中
} }
/// <summary> /// <summary>
@ -34,8 +38,12 @@ namespace OpenAuth.App
{ {
var result = new List<KeyDescription>(); var result = new List<KeyDescription>();
const string domain = "openauth.repository.domain."; const string domain = "openauth.repository.domain.";
var entity = _context.Model.GetEntityTypes() IEntityType entity = null;
.FirstOrDefault(u => u.Name.ToLower()==domain + moduleName.ToLower()); _contexts.ForEach(u =>
{
entity = u.Model.GetEntityTypes()
.FirstOrDefault(u => u.Name.ToLower() == domain + moduleName.ToLower());
});
if (entity == null) if (entity == null)
{ {
throw new Exception($"未能找到{moduleName}对应的实体类"); throw new Exception($"未能找到{moduleName}对应的实体类");
@ -74,14 +82,17 @@ namespace OpenAuth.App
public List<string> GetDbEntityNames() public List<string> GetDbEntityNames()
{ {
var names = new List<string>(); var names = new List<string>();
var model = _context.Model; var models = _contexts.Select(u =>u.Model);
// Get all the entity types information contained in the DbContext class, ... foreach (var model in models)
var entityTypes = model.GetEntityTypes();
foreach (var entityType in entityTypes)
{ {
var tableNameAnnotation = entityType.GetAnnotation("Relational:TableName"); // Get all the entity types information contained in the DbContext class, ...
names.Add(tableNameAnnotation.Value.ToString()); var entityTypes = model.GetEntityTypes();
foreach (var entityType in entityTypes)
{
var tableNameAnnotation = entityType.GetAnnotation("Relational:TableName");
names.Add(tableNameAnnotation.Value.ToString());
}
} }
return names; return names;
@ -109,8 +120,15 @@ namespace OpenAuth.App
/// </summary> /// </summary>
/// <param name="tableName"></param> /// <param name="tableName"></param>
/// <returns></returns> /// <returns></returns>
private IList<SysTableColumn> GetMySqlStructure(string tableName) private IList<SysTableColumn> GetMySqlStructure(string dbandTableName)
{ {
if (!dbandTableName.Contains("."))
{
throw new Exception("代码生成器使用mysql时表名必需用【schemeName.tableName】形式");
}
var splits = dbandTableName.Split(".");
var tableName = splits[1];
var schemeName = splits[0];
var sql = $@"SELECT DISTINCT var sql = $@"SELECT DISTINCT
Column_Name AS ColumnName, Column_Name AS ColumnName,
'{ tableName}' as tableName, '{ tableName}' as tableName,
@ -156,34 +174,22 @@ namespace OpenAuth.App
FROM FROM
information_schema.COLUMNS information_schema.COLUMNS
WHERE WHERE
table_name = '{tableName}' {GetMysqlTableSchema()}"; table_name = '{tableName}' {schemeName}";
var columns = _context.Query<SysTableColumn>().FromSqlRaw(sql); foreach (var context in _contexts)
return columns.ToList();
}
/// <summary>
/// 获取mysql当前的数据库名称
/// </summary>
/// <returns></returns>
private string GetMysqlTableSchema()
{
try
{ {
string dbName = _context.Database.GetDbConnection().ConnectionString.Split("Database=")[1].Split(";")[0]?.Trim(); var columns = context.Query<SysTableColumn>().FromSqlRaw(sql);
if (!string.IsNullOrEmpty(dbName)) var columnList = columns?.ToList();
if (columnList != null && columnList.Any())
{ {
dbName = $" and table_schema = '{dbName}' "; return columnList;
} }
return dbName;
}
catch (Exception ex)
{
Console.WriteLine($"获取mysql数据库名异常:{ex.Message}");
return "";
} }
return new List<SysTableColumn>();
} }
/// <summary> /// <summary>
/// 获取SqlServer表结构信息 /// 获取SqlServer表结构信息
@ -276,8 +282,16 @@ namespace OpenAuth.App
WHERE obj.name = '{ tableName}') AS t WHERE obj.name = '{ tableName}') AS t
ORDER BY t.colorder"; ORDER BY t.colorder";
var columns = _context.Query<SysTableColumn>().FromSqlRaw(sql); foreach (var context in _contexts)
return columns.ToList(); {
var columns = context.Query<SysTableColumn>().FromSqlRaw(sql);
var columnList = columns?.ToList();
if (columnList != null && columnList.Any())
{
return columnList;
}
}
return new List<SysTableColumn>();
} }
} }
} }

View File

@ -272,8 +272,8 @@ namespace OpenAuth.App
FlowRuntime wfruntime = new FlowRuntime(flowInstance); FlowRuntime wfruntime = new FlowRuntime(flowInstance);
string resnode = ""; string rejectNode = ""; //驳回的节点
resnode = string.IsNullOrEmpty(reqest.NodeRejectStep) ? wfruntime.RejectNode(reqest.NodeRejectType) : reqest.NodeRejectStep; rejectNode = string.IsNullOrEmpty(reqest.NodeRejectStep) ? wfruntime.RejectNode(reqest.NodeRejectType) : reqest.NodeRejectStep;
var tag = new Tag var tag = new Tag
{ {
@ -285,13 +285,13 @@ namespace OpenAuth.App
wfruntime.MakeTagNode(wfruntime.currentNodeId, tag); wfruntime.MakeTagNode(wfruntime.currentNodeId, tag);
flowInstance.IsFinish = 4;//4表示驳回需要申请者重新提交表单 flowInstance.IsFinish = 4;//4表示驳回需要申请者重新提交表单
if (resnode != "") if (rejectNode != "")
{ {
flowInstance.PreviousId = flowInstance.ActivityId; flowInstance.PreviousId = flowInstance.ActivityId;
flowInstance.ActivityId = resnode; flowInstance.ActivityId = rejectNode;
flowInstance.ActivityType = wfruntime.GetNodeType(resnode); flowInstance.ActivityType = wfruntime.GetNodeType(rejectNode);
flowInstance.ActivityName = wfruntime.Nodes[resnode].name; flowInstance.ActivityName = wfruntime.Nodes[rejectNode].name;
flowInstance.MakerList = GetNodeMarkers(wfruntime.Nodes[resnode]);//当前节点可执行的人信息 flowInstance.MakerList = GetNodeMarkers(wfruntime.Nodes[rejectNode], flowInstance.CreateUserId);
AddTransHistory(wfruntime); AddTransHistory(wfruntime);
} }
@ -416,11 +416,14 @@ namespace OpenAuth.App
/// </summary> /// </summary>
/// <param name="node"></param> /// <param name="node"></param>
/// <returns></returns> /// <returns></returns>
private string GetNodeMarkers(FlowNode node) private string GetNodeMarkers(FlowNode node,string flowinstanceCreateUserId="")
{ {
string makerList = ""; string makerList = "";
if (node.type == FlowNode.START && (!string.IsNullOrEmpty(flowinstanceCreateUserId))) //如果是开始节点,通常情况下是驳回到开始了
if (node.setInfo != null) {
makerList = flowinstanceCreateUserId;
}
else if (node.setInfo != null)
{ {
if (node.setInfo.NodeDesignate == Setinfo.ALL_USER)//所有成员 if (node.setInfo.NodeDesignate == Setinfo.ALL_USER)//所有成员
{ {

View File

@ -0,0 +1,40 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Interface;
namespace OpenAuth.App
{
/// <summary>
/// 主键为numberic类型的业务使用BaseLongApp基类
/// </summary>
public class IntAutoGenApp :BaseIntAutoGenApp<IntAutoGen, OpenAuthDBContext>
{
public void Add(IntAutoGen application)
{
Repository.Add(application);
}
public void Update(IntAutoGen application)
{
Repository.Update(application);
}
public async Task<List<IntAutoGen>> GetList(QueryAppListReq request)
{
var applications = UnitWork.Find<IntAutoGen>(null) ;
return applications.ToList();
}
public IntAutoGenApp(IUnitWork<OpenAuthDBContext> unitWork, IRepository<IntAutoGen,OpenAuthDBContext> repository,IAuth auth)
: base(unitWork, repository, auth)
{
}
}
}

View File

@ -1,4 +1,5 @@
using System.Net.Http; using System;
using System.Net.Http;
using Infrastructure; using Infrastructure;
using Infrastructure.Cache; using Infrastructure.Cache;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
@ -7,6 +8,7 @@ using Microsoft.Extensions.DependencyInjection;
using Moq; using Moq;
using OpenAuth.App.Request; using OpenAuth.App.Request;
using OpenAuth.App.SSO; using OpenAuth.App.SSO;
using Yitter.IdGenerator;
namespace OpenAuth.App.Test namespace OpenAuth.App.Test
{ {
@ -19,7 +21,7 @@ namespace OpenAuth.App.Test
var services = new ServiceCollection(); var services = new ServiceCollection();
var cachemock = new Mock<ICacheContext>(); var cachemock = new Mock<ICacheContext>();
cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = "test3" }); cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = "admin" });
services.AddScoped(x => cachemock.Object); services.AddScoped(x => cachemock.Object);
//模拟服务端httpContext //模拟服务端httpContext
@ -33,6 +35,24 @@ namespace OpenAuth.App.Test
return services; return services;
} }
[Test]
public void Create()
{
var options = new IdGeneratorOptions(){ WorkerId = 1};
IIdGenerator idHelper = new YitIdGenerator(options);
var code = idHelper.NewLong().ToString();
var app = _autofacServiceProvider.GetService<FlowInstanceApp>();
app.CreateInstance(new AddFlowInstanceReq
{
SchemeId = "18a34903-175b-4cfb-9947-db67b538bbc8",
FrmType = 2,
FrmData = "{\"WorkDate\":\"2021-03-15\",\"Time\":\"8\",\"Reason\":\"dsdsds\"}",
CustomName = DateTime.Now.ToString(),
Code = code
});
}
[Test] [Test]
@ -41,8 +61,8 @@ namespace OpenAuth.App.Test
var app = _autofacServiceProvider.GetService<FlowInstanceApp>(); var app = _autofacServiceProvider.GetService<FlowInstanceApp>();
app.Verification(new VerificationReq app.Verification(new VerificationReq
{ {
FlowInstanceId = "76c72db4-d6c8-4734-856e-b6ffee08314a", FlowInstanceId = "c2d6d4b9-527d-426e-98db-1d5dc905a994",
VerificationFinally = "1" VerificationFinally = "3"
}); });
} }
} }

View File

@ -0,0 +1,31 @@
using System;
using NUnit.Framework;
using Microsoft.Extensions.DependencyInjection;
using OpenAuth.Repository.Domain;
namespace OpenAuth.App.Test
{
public class TestIntAutoGenApp :TestBase
{
[Test]
public void Add()
{
var app = _autofacServiceProvider.GetService<IntAutoGenApp>();
var intAutoGen = new IntAutoGen
{
Name = DateTime.Now.ToString()
};
app.Add(intAutoGen);
Console.WriteLine($"new Id:{intAutoGen.Id}");
}
[Test]
public void Del()
{
var app = _autofacServiceProvider.GetService<IntAutoGenApp>();
app.Delete(new []{1, 2});
}
}
}