框架重构

清除多余的业务
This commit is contained in:
橙子
2022-04-03 23:21:53 +08:00
parent f5fb2ea17b
commit f0d32af3c3
936 changed files with 213647 additions and 86 deletions

View File

@@ -0,0 +1,31 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:49970",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"WebFirst.Api": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,26 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace @Model.name_space
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}

View File

@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

View File

@@ -0,0 +1,86 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace @Model.name_space{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebFirst.Api", Version = "v1" });
});
//配置JSON.NET
services.AddControllers().AddNewtonsoftJson(opt =>
{
//忽略循环引用
opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//不改变字段大小
opt.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
//配置可以跨域
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder => builder.AllowAnyOrigin()
.AllowAnyHeader()
.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.InjectJavascript("");
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API");
c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
c.DefaultModelsExpandDepth(-1);
});
}
app.UseCors(MyAllowSpecificOrigins);//添加这个
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

View File

@@ -0,0 +1,76 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using WebFirst.Entities;
namespace @Model.name_space
{
public class @(Model.ClassName)Manager : Repository<@Model.ClassName>
{
//当前类已经继承了 Repository 增、删、查、改的方法
//这里面写的代码不会给覆盖,如果要重新生成请删除 @(Model.ClassName)Manager.cs
#region 教学方法
/// <summary>
/// 仓储方法满足不了复杂业务需求,业务代码请在这里面定义方法
/// </summary>
public void Study()
{
/*********查询*********/
var data1 = base.GetById(1);//根据ID查询
var data2 = base.GetList();//查询所有
var data3 = base.GetList(it => 1 == 1); //根据条件查询
//var data4 = base.GetSingle(it => 1 == 1);//根据条件查询一条,如果超过一条会报错
var p = new PageModel() { PageIndex = 1, PageSize = 2 };// 分页查询
var data5 = base.GetPageList(it => 1 == 1, p);
Console.Write(p.TotalCount);//返回总数
var data6 = base.GetPageList(it => 1 == 1, p, it => SqlFunc.GetRandom(), OrderByType.Asc);// 分页查询加排序
Console.Write(p.TotalCount);//返回总数
List<IConditionalModel> conModels = new List<IConditionalModel>(); //组装条件查询作为条件实现 分页查询加排序
conModels.Add(new ConditionalModel() { FieldName= typeof(@Model.ClassName).GetProperties()[0].Name, ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1
var data7 = base.GetPageList(conModels, p, it => SqlFunc.GetRandom(), OrderByType.Asc);
base.AsQueryable().Where(x => 1 == 1).ToList();//支持了转换成queryable,我们可以用queryable实现复杂功能
/*********插入*********/
var insertData = new @(Model.ClassName)() { };//测试参数
var insertArray = new @(Model.ClassName)[] { insertData };
base.Insert(insertData);//插入
base.InsertRange(insertArray);//批量插入
var id = base.InsertReturnIdentity(insertData);//插入返回自增列
base.AsInsertable(insertData).ExecuteCommand();//我们可以转成 Insertable实现复杂插入
/*********更新*********/
var updateData = new @(Model.ClassName)() { };//测试参数
var updateArray = new @(Model.ClassName)[] { updateData };//测试参数
base.Update(updateData);//根据实体更新
base.UpdateRange(updateArray);//批量更新
//base.Update(it => new @(Model.ClassName)() { ClassName = "a", CreateTime = DateTime.Now }, it => it.id==1);// 只更新ClassName列和CreateTime列其它列不更新条件id=1
base.AsUpdateable(updateData).ExecuteCommand(); //转成Updateable可以实现复杂的插入
/*********删除*********/
var deldata = new @(Model.ClassName)() { };//测试参数
base.Delete(deldata);//根据实体删除
base.DeleteById(1);//根据主键删除
base.DeleteById(new int[] { 1,2});//根据主键数组删除
base.Delete(it=>1==2);//根据条件删除
base.AsDeleteable().Where(it=>1==2).ExecuteCommand();//转成Deleteable实现复杂的操作
}
#endregion
}
}

View File

@@ -0,0 +1,127 @@
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
namespace @Model.name_space
{
/***这里面写的代码不会给覆盖,如果要重新生成请删除 Repository.cs ***/
/// <summary>
/// 仓储模式
/// </summary>
/// <typeparam name="T"></typeparam>
public class Repository<T> : SimpleClient<T> where T : class, new()
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="context"></param>
public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
{
if (context == null)
{
base.Context = Db;
}
}
/// <summary>
/// SqlSugarScope操作数据库是线程安的可以单例
/// </summary>
public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig()
{
DbType = [请设置DbType],
ConnectionString = [请设置ConStr],
IsAutoCloseConnection = true
},
db =>
{
//如果用单例配置要统一写在这儿
db.Aop.OnLogExecuting = (s, p) =>
{
};
});
/// <summary>
/// 仓储扩展方法:单表查询通用分页
/// </summary>
/// <returns></returns>
public object CommonPage(QueryParameters pars, int pageIndex, int pagesize)
{
int tolCount = 0;
var sugarParamters = pars.Parameters.Select(it => (IConditionalModel)new ConditionalModel()
{
ConditionalType = it.ConditionalType,
FieldName = it.FieldName,
FieldValue = it.FieldValue
}).ToList();
var query = Db.Queryable<T>();
if (pars.OrderBys != null)
{
foreach (var item in pars.OrderBys)
{
query.OrderBy(item.ToSqlFilter());//格式 id asc或者 id desc
}
}
var result = query.Where(sugarParamters).ToPageList(1, 2, ref tolCount);
return new
{
count = tolCount,
data = result
};
}
/// <summary>
/// 仓储扩展方法:多表查询通用分页
/// 用法 CommonPage(db.Queryable<JoinTable1,JoinTable2>(...).Select(it=new class(){..}).MergeTable(),pars,orderbys,pageIndex,pagesize)
/// </summary>
/// <returns></returns>
public object CommonPage<ViewModel>(ISugarQueryable<ViewModel> query, QueryParameters pars, int pageIndex, int pagesize)
{
int tolCount = 0;
var sugarParamters = pars.Parameters.Select(it => (IConditionalModel)new ConditionalModel()
{
ConditionalType = it.ConditionalType,
FieldName = it.FieldName,
FieldValue = it.FieldValue
}).ToList();
if (pars.OrderBys != null)
{
foreach (var item in pars.OrderBys)
{
query.OrderBy(item.ToSqlFilter());//格式 id asc或者 id desc
}
}
var result = query.Where(sugarParamters).ToPageList(1, 2, ref tolCount);
return new
{
count = tolCount,
data = result
};
}
}
/// <summary>
/// 通用查询参数
/// </summary>
public class QueryParameters
{
public List<QueryParameter> Parameters { get; set; }
public List<string> OrderBys { get; set; }
}
/// <summary>
/// 通用查询参数
/// </summary>
public class QueryParameter
{
public string FieldName { get; set; }
public string FieldValue { get; set; }
public ConditionalType ConditionalType
{
get; set;
}
}
}

View File

@@ -0,0 +1 @@
{"name":"DbContext", "name_space":"命名空间" }

View File

@@ -0,0 +1 @@
{"name":"文件名"}

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using SqlSugar;
namespace @Model.name_space
{
/// <summary>
/// @((Model.Description+"").Replace("\r","").Replace("\n",""))
///</summary>
[SugarTable("@(Model.TableName)")]
public class @(Model.ClassName)
{
@foreach (var item in Model.PropertyGens)
{
var isPrimaryKey = item.IsPrimaryKey ? ",IsPrimaryKey = true" : "";
var isIdentity = item.IsIdentity ? ",IsIdentity = true" : "";
var isNull=(item.IsNullable&&item.Type!="string"&&item.IsSpecialType==false&&item.Type!="byte[]")?"?":"";
var isIgnore=(item.IsIgnore?",IsIgnore = true":"");
var isJson=(item.CodeType.StartsWith("json")?",IsJson= true":"");
var newPropertyName=item.PropertyName; //这里可以用C#处理 实体属性的显式格式
//想和数据库一样就用 newPropertyName=item.DbColumnName
if(System.Text.RegularExpressions.Regex.IsMatch(newPropertyName.Substring(0,1), "[0-9]"))
{
newPropertyName="_"+newPropertyName;//处理属性名开头为数字情况
}
if(newPropertyName==Model.ClassName)
{
newPropertyName="_"+newPropertyName;//处理属性名不能等于类名
}
var desc=(item.Description+"").Replace("\r","").Replace("\n","");//处理换行
if(isIgnore!="")
{
isPrimaryKey =isIdentity =isNull="";
}
@:/// <summary>
@:/// @(desc)
@if(item.DefaultValue!=null)
{
@:/// 默认值: @Raw(item.DefaultValue)
}
@:///</summary>
@: [SugarColumn(ColumnName="@item.DbColumnName" @(isPrimaryKey) @(isIdentity) @(isIgnore) @(isJson))]
@: public @Raw(item.Type)@isNull @newPropertyName { get; set; }
}
}
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace>@Model.name</RootNamespace>
<AssemblyName>@Model.name</AssemblyName>
</PropertyGroup>
<ItemGroup>
@foreach(var item in Model.nuget)
{
<PackageReference Include="@item.name" Version="@item.version" />
}
</ItemGroup>
@Raw(Model.reference)
</Project>

View File

@@ -0,0 +1 @@
{ "name":"命名空间类库名","nuget":[{ "name":"SqlSugarCore","version":"5.0.3.4" }]}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<RootNamespace>@Model.name</RootNamespace>
<AssemblyName>@Model.name</AssemblyName>
</PropertyGroup>
<ItemGroup>
@foreach(var item in Model.nuget)
{
<PackageReference Include="@item.name" Version="@item.version" />
}
</ItemGroup>
@Raw(Model.reference)
</Project>

View File

@@ -0,0 +1,29 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31624.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "{0}", "{1}", "{9FF70A7E-AF60-41B4-A0D7-A5C31B04E192}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9FF70A7E-AF60-41B4-A0D7-A5C31B04E192}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9FF70A7E-AF60-41B4-A0D7-A5C31B04E192}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9FF70A7E-AF60-41B4-A0D7-A5C31B04E192}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9FF70A7E-AF60-41B4-A0D7-A5C31B04E192}.Release|Any CPU.Build.0 = Release|Any CPU
{ECAF5815-8237-4522-B75C-1E35CD8A675D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ECAF5815-8237-4522-B75C-1E35CD8A675D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ECAF5815-8237-4522-B75C-1E35CD8A675D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ECAF5815-8237-4522-B75C-1E35CD8A675D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DAFECE02-00B6-4790-975F-B20F41C17EAC}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,100 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebFirst.Entities;
using WebFirst.Services;
namespace @(Model.name_space).Controllers
{
[ApiController]
[Route("[controller]")]
public class @(Model.ClassName)Controller : ControllerBase
{
private @(Model.ClassName)Manager m = new @(Model.ClassName)Manager();
/***进入模版管理可以修改模版***/
/// <summary>
/// 获取所有
/// </summary>
/// <returns></returns>
[Route("GetList"), HttpPost]
public List<@(Model.ClassName)> GetList()
{
var result = m.GetList();
return result;
}
/// <summary>
/// 根据主键获取
/// </summary>
/// <returns></returns>
[Route("GetById"), HttpPost]
public @(Model.ClassName) GetById(int id)
{
var result = m.GetById(id);
return result;
}
/// <summary>
/// 根据主键删除
/// </summary>
/// <returns></returns>
[Route("DeleteByIds"), HttpPost]
public bool DeleteByIds([FromBody]object[] ids)
{
var result = m.DeleteByIds(ids);
return result;
}
/// <summary>
/// 添加
/// </summary>
/// <returns></returns>
[Route("Insert"), HttpPost]
public bool Add([FromBody] @(Model.ClassName) data)
{
var result = m.Insert(data);
return result;
}
/// <summary>
/// 添加返回自增
/// </summary>
/// <returns></returns>
[Route("InsertReturnIdentity"), HttpPost]
public int InsertReturnIdentity([FromBody] @(Model.ClassName) data)
{
var result = m.InsertReturnIdentity(data);
return result;
}
/// <summary>
/// 修改
/// </summary>
/// <returns></returns>
[Route("Update"), HttpPost]
public bool Update([FromBody] @(Model.ClassName) data)
{
var result = m.Update(data);
return result;
}
/// <summary>
/// 通用分页
/// </summary>
/// <returns></returns>
[Route("CommonPage"),HttpPost]
public object CommonPage([FromBody]QueryParameters pars,int pageIndex,int pagesize)
{
var result= m.CommonPage(pars, pageIndex, pagesize);
return result;
}
}
}

View File

@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
@foreach(var item in Model.nuget)
{
<PackageReference Include="@item.name" Version="@item.version" />
}
</ItemGroup>
@Raw(Model.reference)
</Project>