Commit b3c81e9e by 赵剑炜

调整方法至可用

parent 1baa8574
...@@ -7,6 +7,10 @@ ...@@ -7,6 +7,10 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Remove="Controllers\JwtController.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="11.0.0" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="11.0.0" />
<PackageReference Include="FluentValidation.AspNetCore" Version="10.4.0" /> <PackageReference Include="FluentValidation.AspNetCore" Version="10.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.4" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.4" />
......
using APIs.Dto; using APIs.Dto;
using AutoMapper; using AutoMapper;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Models; using Models.SqlModel;
using Services.Interface;
namespace APIs.Controllers namespace APIs.Controllers
{ {
...@@ -10,18 +11,30 @@ namespace APIs.Controllers ...@@ -10,18 +11,30 @@ namespace APIs.Controllers
public class MapperController : ControllerBase public class MapperController : ControllerBase
{ {
public IMapper Mapper { get; } public IMapper Mapper { get; }
private readonly IUserService _tService;
public MapperController(IMapper mapper)
public MapperController(IMapper mapper, IUserService userService)
{ {
_tService=userService;
Mapper = mapper; Mapper = mapper;
} }
[HttpPost] [HttpPost]
public UserDto Test(User user) public UserDto Test(Users user)
{ {
var userDto = new UserDto(); var userDto = new UserDto();
Mapper.Map(user, userDto); Mapper.Map(user, userDto);
return userDto; return userDto;
}
[HttpGet]
public UserDto GetTest()
{
var userDto = new UserDto();
List<Users> aa= _tService.GetData();
Mapper.Map(aa, userDto);
return userDto;
} }
} }
} }
......
using APIs.Dto;
using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Models.SqlModel;
using Models.ToolsModel;
using Services;
using Services.Interface;
namespace APIs.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : Controller
{
public IMapper Mapper { get; }
private readonly IPoliceService _policeService;
public UserController(IMapper mapper, IPoliceService policeService)
{
_policeService = policeService;
Mapper = mapper;
}
[HttpGet]
public virtual async Task<ApiResult> GetAllPersonnel()
{
ApiResult result = new ApiResult();
try
{
var userDto = new UserDto();
var police = await _policeService.Query();
//var userInfo = await _userInfo.QueryOne(x => x.UserName == model.UserName && x.PassWord == model.PassWord);
result.data = police;
result.code = 1;
return result;
}
catch (Exception ex)
{
result.code = 0;
result.msg = "失败";
return result;
}
}
}
}
using Microsoft.AspNetCore.Mvc;
namespace APIs.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
\ No newline at end of file
using SqlSugar; using SqlSugar;
namespace WebApiNet6.Extensions; namespace APIs.Extensions;
public static class SqlsugarSetup public static class SqlsugarSetup
{ {
public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration, public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration,
string dbName = "MySQL") string dbName = "MySQL")
{ {
SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig() var a = configuration.GetConnectionString(dbName);
services.AddScoped<ISqlSugarClient>(o =>
{ {
DbType = SqlSugar.DbType.MySql, var listConfig = new List<ConnectionConfig>();
ConnectionString = configuration.GetConnectionString(dbName), listConfig.Add(new ConnectionConfig()
IsAutoCloseConnection = true,
}, db =>
{
db.Aop.OnLogExecuting = (sql, pars) =>
{ {
//Console.WriteLine(sql); ConnectionString = configuration.GetConnectionString(dbName),
}; DbType = (SqlSugar.DbType)DbType.MySql,
IsAutoCloseConnection = true,
MoreSettings = new ConnMoreSettings()
{
IsAutoRemoveDataCache = true
}
});
return new SqlSugarClient(listConfig);
}); });
services.AddSingleton<ISqlSugarClient>(sqlSugar);
} }
} }
\ No newline at end of file
using APIs.Dto; using APIs.Dto;
using AutoMapper; using AutoMapper;
using Models; using Models.SqlModel;
namespace APIs.Profiles; namespace APIs.Profiles;
......
using System.Configuration;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Xml.Linq;
using APIs.Extensions;
using APIs.Profiles; using APIs.Profiles;
using Common; using Common;
using FluentValidation.AspNetCore; using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Repositories; using Repositories;
using WebApiNet6.Extensions; using Repositories.IRepository.IBussiness;
using Repositories.IRepository.IUnitOfWork;
using Repositories.Repository.Bussiness;
using Repositories.Repository.UnitOfWork;
using Services;
using Services.Interface;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container. // Add services to the container.
builder.Services.AddSqlsugarSetup(builder.Configuration); builder.Services.AddSqlsugarSetup(builder.Configuration);
builder.Services.AddMemoryCache(); builder.Services.AddMemoryCache();
builder.Services.AddControllers() builder.Services.AddControllers()
.AddNewtonsoftJson(options => .AddNewtonsoftJson(options =>
{ {
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
}); });
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
...@@ -24,61 +36,34 @@ builder.Services.AddEndpointsApiExplorer(); ...@@ -24,61 +36,34 @@ builder.Services.AddEndpointsApiExplorer();
builder.Services.AddAutoMapper(typeof(MapperProfile)); builder.Services.AddAutoMapper(typeof(MapperProfile));
builder.Services.AddSwaggerGen(options => builder.Services.AddSwaggerGen(options =>
{ {
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() //options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{ //{
Description = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token", // Description = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token",
Name = "Authorization", // Name = "Authorization",
In = ParameterLocation.Header, // In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey, // Type = SecuritySchemeType.ApiKey,
BearerFormat = "Jwt", // BearerFormat = "Jwt",
Scheme = "Bearer" // Scheme = "Bearer"
}); //});
options.AddSecurityRequirement(new OpenApiSecurityRequirement //options.AddSecurityRequirement(new OpenApiSecurityRequirement
{ //{
{ // {
new OpenApiSecurityScheme // new OpenApiSecurityScheme
{ // {
Reference = new OpenApiReference // Reference = new OpenApiReference
{ // {
Type = ReferenceType.SecurityScheme, // Type = ReferenceType.SecurityScheme,
Id = "Bearer" // Id = "Bearer"
} // }
}, // },
new string[] {} // new string[] {}
} // }
}); ////});
}); });
builder.Services.AddScoped<ISugarUnitOfWork, SugarUnitOfWork>();
builder.Services.AddScoped<IPoliceService, PoliceService>();
builder.Services.AddScoped<IPoliceRepository, PoliceRepository>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
var tokenModel = builder.Configuration.GetSection("Jwt").Get<JwtHelper.TokenModelJwt>();
var secretByte = Encoding.UTF8.GetBytes(tokenModel.Secret);
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuer = tokenModel.Issuer,
ValidateAudience = true,
ValidAudience = tokenModel.Audience,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(secretByte)
};
options.Events = new JwtBearerEvents()
{
OnChallenge = context =>
{
return Task.FromResult(0);
},
OnForbidden = context =>
{
return Task.FromResult(0);
}
};
});
builder.Services.AddScoped(typeof(Repository<>));
builder.Services.AddFluentValidation(options => builder.Services.AddFluentValidation(options =>
{ {
...@@ -95,9 +80,9 @@ builder.Services.AddCors(options => ...@@ -95,9 +80,9 @@ builder.Services.AddCors(options =>
}); });
}); });
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {
app.UseSwagger(); app.UseSwagger();
......
using FluentValidation; using FluentValidation;
using Models; using Models.SqlModel;
namespace APIs.Validators; namespace APIs.Validators;
......
...@@ -7,11 +7,11 @@ ...@@ -7,11 +7,11 @@
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"ConnectionStrings": { "ConnectionStrings": {
"MySQL": "server=localhost;port=3306;Database=WebApiNet6;Uid=root;Pwd=123456;" "MySQL": "server=192.168.3.128;port=3306;Database=xuzhou;Uid=junmp;Pwd=123456;"
},
"Jwt": {
"Secret": "f30386a4fc41d3c1a75cd7f3de54c48c",
"Issuer": "Atlantis",
"Audience": "Atlantis"
} }
//"Jwt": {
// "Secret": "f30386a4fc41d3c1a75cd7f3de54c48c",
// "Issuer": "Atlantis",
// "Audience": "Atlantis"
//}
} }
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
......
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace Models.SqlModel
{
[SugarTable("base_personnel")]
public class Police
{
[SugarColumn( IsIdentity = true, IsPrimaryKey = true)]
public String id { get; set; }
public String name { get; set; }
public String policecode { get; set; }
public String? phone { get; set; }
[SugarColumn(ColumnName = "id_card")]
public String? idCard { get; set; }
public String? sex { get; set; }
[SugarColumn(ColumnName = "update_time")]
public DateTime? updateTime { get; set; }
[SugarColumn(ColumnName = "create_time")]
public DateTime? createTime { get; set; }
}
}
using SqlSugar; using SqlSugar;
namespace Models; namespace Models.SqlModel;
public class User public class User
{ {
[SugarColumn(IsIdentity = true, IsPrimaryKey = true)] [SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
public int Id { get; set; } public int Id { get; set; }
public string UserName { get; set; } public string UserName { get; set; }
public int Age { get; set; } public int Age { get; set; }
} }
\ No newline at end of file
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace Models.SqlModel
{
[SugarTable("sys_user")]
public class Users
{
[SugarColumn(ColumnName= "user_id", IsIdentity = true, IsPrimaryKey = true)]
public String userId { get; set; }
[SugarColumn(ColumnName = "real_name")]
public String realName { get; set; }
[SugarColumn(ColumnName = "nick_name")]
public String nickName { get; set; }
[SugarColumn(ColumnName = "account")]
public String? Account { get; set; }
public String? password { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Models.ToolsModel
{
public class ApiResult
{
public ApiResult()
{
IsSuccess = true;
code = 200;
msg = "";
data = "";
}
public bool IsSuccess { get; set; }
public int code { get; set; }
//public int statusCode { get; set; }
public object data { get; set; }
public string msg { get; set; }
#region list info
public int page { get; set; }
public int count { get; set; }
public int total { get; set; }
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Models.ToolsModel
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseResponse<T>
{
public static BaseResponse<T> GetResponse(T t, StatusCode code, string msg)
{
return new BaseResponse<T>() { code = code, msg = msg, data = t == null ? default(T) : t };
}
public string msg { get; set; }
public StatusCode code { get; set; }
public T data { get; set; }
}
public enum StatusCode
{
/// <summary>
/// 成功
/// </summary>
Success = 1,
/// <summary>
/// 失败
/// </summary>
Fail = 2,
/// <summary>
/// 参数为空
/// </summary>
ParamsNull = 3,
/// <summary>
///
/// </summary>
NoAccess = 4,
/// <summary>
/// Token失效
/// </summary>
ErrorToken = 5,
/// <summary>
/// 没有权限
/// </summary>
ErrorAuth = 6,
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Models.ToolsModel
{
public class PageModel<T>
{
/// <summary>
/// 当前页标
/// </summary>
public int page { get; set; } = 1;
/// <summary>
/// 总页数
/// </summary>
public int pageCount { get; set; } = 0;
/// <summary>
/// 数据总数
/// </summary>
public int dataCount { get; set; } = 0;
/// <summary>
/// 每页大小
/// </summary>
public int PageSize { set; get; }
/// <summary>
/// 返回数据
/// </summary>
public List<T> Children { get; set; }
}
}
using Models.ToolsModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Repositories.IRepository
{
public interface IBaseRepository<TEntity> where TEntity : class
{
Task<int> Add(TEntity entity);
Task<int> Add(List<TEntity> listEntity);
Task<bool> Update(TEntity entity);
Task<bool> DeleteByIds(int[] ids);
Task<bool> DeleteById(object id);
Task<TEntity> QueryOne(Expression<Func<TEntity, bool>> whereExpress);
Task<TEntity> QueryOneOrderDesc(Expression<Func<TEntity, bool>> whereExpresson, Expression<Func<TEntity, object>> orderExpression);
Task<TEntity> QueryOneOrder(Expression<Func<TEntity, bool>> whereExpresson, Expression<Func<TEntity, object>> orderExpression);
Task<List<TEntity>> Query();
Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression);
Task<PageModel<TEntity>> QueryPage(Expression<Func<TEntity, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null);
Task<PageModel<TResult>> QueryMuch<T, T2, T3, TResult>(
int intPageIndex,
int intPageSize,
string strOrderByFileds,
string where,
Expression<Func<T, T2, T3, object[]>> joinExpression,
Expression<Func<T, T2, T3, TResult>> selectExpression
) where T : class, new();
}
}
using Models.SqlModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repositories.IRepository.IBussiness
{
public interface IPoliceRepository : IBaseRepository<Police>
{
}
}
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repositories.IRepository.IUnitOfWork
{
public interface ISugarUnitOfWork : IDisposable
{
SqlSugarClient GetDbClient();
void BeginTran();
void CommitTran();
void RollbackTran();
}
}
...@@ -7,6 +7,10 @@ ...@@ -7,6 +7,10 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Remove="Repository.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Models\Models.csproj" /> <ProjectReference Include="..\Models\Models.csproj" />
</ItemGroup> </ItemGroup>
......
using Models.ToolsModel;
using Repositories.IRepository;
using SqlSugar.Extensions;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Repositories.IRepository.IUnitOfWork;
namespace Repositories.Repository
{
public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class, new()
{
private ISugarUnitOfWork _db;
public BaseRepository(ISugarUnitOfWork sugarUnitOfWork)
{
_db = sugarUnitOfWork;
}
public async Task<int> Add(TEntity entity)
{
using (var context = _db.GetDbClient())
{
var insert = context.Insertable(entity);
return await insert.ExecuteReturnIdentityAsync();
}
}
public async Task<bool> Update(TEntity entity)
{
using (var context = _db.GetDbClient())
{
return await context.Updateable(entity).ExecuteCommandHasChangeAsync();
}
}
public async Task<bool> DeleteByIds(int[] ids)
{
using (var context = _db.GetDbClient())
{
return await context.Deleteable<TEntity>().In(ids).ExecuteCommandHasChangeAsync();
}
}
public async Task<bool> DeleteById(object id)
{
using (var context = _db.GetDbClient())
{
return await context.Deleteable<TEntity>(id).ExecuteCommandHasChangeAsync();
}
}
public async Task<List<TEntity>> Query()
{
using (var context = _db.GetDbClient())
{
return await context.Queryable<TEntity>().ToListAsync();
}
}
public async Task<TEntity> QueryOneOrderDesc(Expression<Func<TEntity, bool>> whereExpresson, Expression<Func<TEntity, object>> orderExpression)
{
using (var context = _db.GetDbClient())
{
return await context.Queryable<TEntity>().WhereIF(whereExpresson != null, whereExpresson).OrderBy(orderExpression, OrderByType.Desc).FirstAsync();
}
}
public async Task<TEntity> QueryOneOrder(Expression<Func<TEntity, bool>> whereExpresson, Expression<Func<TEntity, object>> orderExpression)
{
using (var context = _db.GetDbClient())
{
return await context.Queryable<TEntity>().WhereIF(whereExpresson != null, whereExpresson).OrderBy(orderExpression).FirstAsync();
}
}
public async Task<TEntity> QueryOne(Expression<Func<TEntity, bool>> whereExpress)
{
using (var context = _db.GetDbClient())
{
return await context.Queryable<TEntity>().WhereIF(whereExpress != null, whereExpress).FirstAsync();
}
}
public async Task<int> Add(List<TEntity> listEntity)
{
using (var context = _db.GetDbClient())
{
return await context.Insertable(listEntity.ToArray()).ExecuteCommandAsync();
}
}
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression)
{
using (var context = _db.GetDbClient())
{
return await context.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).ToListAsync();
}
}
public async Task<PageModel<TEntity>> QueryPage(
Expression<Func<TEntity, bool>> whereExpression,
int intPageIndex = 1,
int intPageSize = 20,
string strOrderByFileds = null)
{
using (var context = _db.GetDbClient())
{
RefAsync<int> totalCount = 0;
var list = await context.Queryable<TEntity>()
.OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
.WhereIF(whereExpression != null, whereExpression)
.ToPageListAsync(intPageIndex, intPageSize, totalCount);
int pageCount = (Math.Ceiling(totalCount.ObjToDecimal() / intPageSize.ObjToDecimal())).ObjToInt();
return new PageModel<TEntity>() { dataCount = totalCount, pageCount = pageCount, page = intPageIndex, PageSize = intPageSize, Children = list };
}
}
public async Task<PageModel<TResult>> QueryMuch<T, T2, T3, TResult>(
int intPageIndex,
int intPageSize,
string strOrderByFileds,
string where,
Expression<Func<T, T2, T3, object[]>> joinExpression,
Expression<Func<T, T2, T3, TResult>> selectExpression
) where T : class, new()
{
using (var context = _db.GetDbClient())
{
RefAsync<int> totalCount = 0;
var list = await context.Queryable(joinExpression)
.OrderByIF(!string.IsNullOrWhiteSpace(strOrderByFileds), strOrderByFileds)
.WhereIF(!string.IsNullOrWhiteSpace(where), where)
.Select(selectExpression)
.ToPageListAsync(intPageIndex, intPageSize, totalCount);
int pageCount = (Math.Ceiling(totalCount.ObjToDecimal() / intPageSize.ObjToDecimal())).ObjToInt();
return new PageModel<TResult>() { dataCount = totalCount, pageCount = pageCount, page = intPageIndex, PageSize = intPageSize, Children = list };
}
}
}
}
using Models.SqlModel;
using Repositories.IRepository.IBussiness;
using Repositories.IRepository.IUnitOfWork;
using Repositories.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repositories.Repository.Bussiness
{
public class PoliceRepository : BaseRepository<Police>, IPoliceRepository
{
public PoliceRepository(ISugarUnitOfWork sugarUnitOfWork) : base(sugarUnitOfWork)
{
}
}
}
using Repositories.IRepository.IUnitOfWork;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repositories.Repository.UnitOfWork
{
public sealed class SugarUnitOfWork : ISugarUnitOfWork
{
private ISqlSugarClient _sqlSugarClient;
public SugarUnitOfWork(ISqlSugarClient sqlSugarClient)
{
_sqlSugarClient = sqlSugarClient;
}
public SqlSugarClient GetDbClient()
{
// 必须要as,后边会用到切换数据库操作
return _sqlSugarClient as SqlSugarClient;
}
public void BeginTran()
{
GetDbClient().BeginTran();
}
public void CommitTran()
{
try
{
GetDbClient().CommitTran();
}
catch (Exception ex)
{
GetDbClient().RollbackTran();
throw ex;
}
}
public void RollbackTran()
{
GetDbClient().RollbackTran();
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
~SugarUnitOfWork()
{
Dispose();
}
}
}
using Models.ToolsModel;
using Repositories.IRepository;
using Services.Interface;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public class BaseService<TEntity> : IBaseServices<TEntity> where TEntity : class, new()
{
protected BaseResponse<T> Result<T>(T t, StatusCode code, string msg)
{
return BaseResponse<T>.GetResponse(t, code, msg);
}
protected BaseResponse<T> Result<T>(T t)
{
return BaseResponse<T>.GetResponse(t, StatusCode.Success, string.Empty);
}
public IBaseRepository<TEntity> BaseDal;
public async Task<int> Add(TEntity entity)
{
return await BaseDal.Add(entity);
}
public async Task<List<TEntity>> Query()
{
return await BaseDal.Query();
}
public async Task<int> Add(List<TEntity> listEntity)
{
return await BaseDal.Add(listEntity);
}
public async Task<bool> DeleteByIds(int[] ids)
{
return await BaseDal.DeleteByIds(ids);
}
public async Task<bool> Update(TEntity entity)
{
return await BaseDal.Update(entity);
}
public async Task<bool> DeleteById(object id)
{
return await BaseDal.DeleteById(id);
}
public async Task<TEntity> QueryOneOrder(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderExpression)
{
return await BaseDal.QueryOneOrder(whereExpression, orderExpression);
}
public async Task<TEntity> QueryOneOrderDesc(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderExpression)
{
return await BaseDal.QueryOneOrderDesc(whereExpression, orderExpression);
}
public async Task<TEntity> QueryOne(Expression<Func<TEntity, bool>> whereExpression)
{
return await BaseDal.QueryOne(whereExpression);
}
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression)
{
return await BaseDal.Query(whereExpression);
}
public async Task<PageModel<TEntity>> QueryPage(Expression<Func<TEntity, bool>> whereExpression,
int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null)
{
return await BaseDal.QueryPage(whereExpression,
intPageIndex, intPageSize, strOrderByFileds);
}
public async Task<PageModel<TResult>> QueryMuch<T, T2, T3, TResult>(
int intPageIndex,
int intPageSize,
string strOrderByFileds,
string where,
Expression<Func<T, T2, T3, object[]>> joinExpression,
Expression<Func<T, T2, T3, TResult>> selectExpression
) where T : class, new()
{
return await BaseDal.QueryMuch(
intPageIndex,
intPageSize,
strOrderByFileds,
where,
joinExpression,
selectExpression
);
}
}
}
using Models.SqlModel;
using Models.ToolsModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Services.Interface
{
public interface IBaseServices<TEntity> where TEntity : class
{
Task<int> Add(TEntity entity);
Task<int> Add(List<TEntity> listEntity);
Task<bool> Update(TEntity entity);
Task<bool> DeleteByIds(int[] ids);
Task<bool> DeleteById(object id);
Task<TEntity> QueryOneOrder(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderExpression);
Task<TEntity> QueryOneOrderDesc(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderExpression);
Task<TEntity> QueryOne(Expression<Func<TEntity, bool>> whereExpression);
Task<List<TEntity>> Query();
Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression);
Task<PageModel<TEntity>> QueryPage(Expression<Func<TEntity, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null);
Task<PageModel<TResult>> QueryMuch<T, T2, T3, TResult>(
int intPageIndex,
int intPageSize,
string strOrderByFileds,
string where,
Expression<Func<T, T2, T3, object[]>> joinExpression,
Expression<Func<T, T2, T3, TResult>> selectExpression
) where T : class, new();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Interface
{
public class IEqSizeService
{
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Interface
{
public interface IEqTypeService
{
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Interface
{
public class IInventoryService
{
}
}
using Models.SqlModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Interface
{
public interface IPoliceService : IBaseServices<Police>
{
}
}
using Models.SqlModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Interface
{
public interface IUserService
{
List<Users> GetData();
}
}
using Models.SqlModel;
using Repositories.IRepository.IBussiness;
using Services.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public class PoliceService : BaseService<Police>, IPoliceService
{
private readonly IPoliceRepository _policeRepository;
public PoliceService(IPoliceRepository policeRepository)
{
base.BaseDal = policeRepository;
_policeRepository = policeRepository;
}
}
}
...@@ -7,6 +7,17 @@ ...@@ -7,6 +7,17 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Remove="Interface\IEqSizeService.cs" />
<Compile Remove="Interface\IEqTypeService.cs" />
<Compile Remove="Interface\IInventoryService.cs" />
<Compile Remove="UserService.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="SqlSugarCore" Version="5.1.4.106" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Repositories\Repositories.csproj" /> <ProjectReference Include="..\Repositories\Repositories.csproj" />
</ItemGroup> </ItemGroup>
......
using Models; using Models.SqlModel;
using Repositories; using Repositories;
using Services.Interface;
namespace Services; namespace Services;
public class UserService public class UserService : IUserService
{ {
public Repository<User> UserRepository { get; } private readonly IRoleRepository _roleRepository;
public UserService(Repository<User> userRepository) public UserService(Repository<User> userRepository, Repository<Users> newUserRepository)
{ {
UserRepository = userRepository; UserRepository = userRepository;
NewUserRepository = newUserRepository;
} }
public List<User> GetUsers() public List<User> GetUsers()
{ {
return UserRepository.GetList(); return UserRepository.GetList();
} }
public List<Users> GetData()
{
return NewUserRepository.GetList();
}
} }
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论