提交 991144aa 编写于 作者: S simon

增加数据访问,api,实体映射等,可以运行,接口测试不正确-2

上级 f283a1bb
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Aurora.Infrastructure\Aurora.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="IdentityModel" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
namespace Aurora.Common
{
public class ConstString
{
public const string CurrentTenantCode = "TenantCode";
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Aurora.Infrastructure.User;
namespace Aurora.Common
{
public class CurrentProvider<T>
{
/// <summary>
/// 租户code
/// </summary>
public string TenantCode { get; set; }
public ICurrentUser CurrentUser { get; set; }
public T RequestEntity { get; set; }
}
}
using System;
namespace Aurora.Common.Entities
{
public class EntityBase
{
public int Id { get; set; }
public DateTimeOffset CreateTime { get; set; }
public string CreateUserName { get; set; }
public DateTimeOffset ModifyTime { get; set; }
public string ModifyUserName { get; set; }
}
}
using System;
namespace Aurora.Common.Entities
{
public class TenantEntityBase : EntityBase
{
public string TenantCode { get; set; }
}
}
using System.Linq;
using System.Security.Claims;
using Aurora.Infrastructure.Permission;
namespace Aurora.Common.Permission
{
public class FunctionPermission : IFunctionPermission
{
public string FunctionCode { get; set; }
public string PermissionCode { get; set; }
}
}
\ No newline at end of file
using System.Linq;
using System.Security.Claims;
using Aurora.Infrastructure.Tenant;
namespace Aurora.Common.Tenant
{
public class CurrentTenant : ICurrentTenant
{
public string TenantCode { get; set; }
}
}
\ No newline at end of file
using IdentityModel;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Security.Claims;
using Aurora.Infrastructure.Tenant;
namespace Aurora.Common.Tenant
{
public class CurrentTenantProvider : ICurrentTenantProvider
{
private CurrentTenant currentTenant { get; set; }
IHttpContextAccessor httpContextAccessor;
public CurrentTenantProvider(IHttpContextAccessor _httpContextAccessor)
{
httpContextAccessor = _httpContextAccessor;
}
public ICurrentTenant GetCurrentTenant()
{
CurrentTenant _currentTenant = new CurrentTenant();
if (httpContextAccessor.HttpContext == null) //cap
{
//todo
_currentTenant = currentTenant;
}
else if (httpContextAccessor.HttpContext.User != null &&
httpContextAccessor.HttpContext.User.Identity.IsAuthenticated) //external
{
ClaimsPrincipal claimsPrincipal = httpContextAccessor.HttpContext.User;
var subject = claimsPrincipal.Claims.FirstOrDefault(w => w.Type == JwtClaimTypes.Role);
_currentTenant.TenantCode = subject.Value;
}
else //internal
{
_currentTenant.TenantCode = httpContextAccessor.HttpContext.Request.Headers[ConstString.CurrentTenantCode].FirstOrDefault();
}
return _currentTenant;
}
}
}
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Aurora.Infrastructure.User;
using Aurora.Infrastructure.Permission;
using Aurora.Common.Permission;
namespace Aurora.Common.User
{
public class CurrentUser : ICurrentUser
{
/// <summary>
/// 用户登录用户Code
/// </summary>
public string UserCode { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 用户名 编码
/// </summary>
// public string NameAndCode { get { return $"{CurrentUserName} {CurrentUserCode}"; } }
/// <summary>
/// 角色Code
/// </summary>
public string RoleCode { get; set; }
/// <summary>
/// 角色Name
/// </summary>
public string RoleName { get; set; }
public List<IFunctionPermission> RolePermission { get; set; }
}
}
using IdentityModel;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Aurora.Infrastructure.User;
namespace Aurora.Common.User
{
public class CurrentUserProvider : ICurrentUserProvider
{
IHttpContextAccessor httpContextAccessor;
IConfiguration _configuration;
public CurrentUserProvider(IHttpContextAccessor _httpContextAccessor, IConfiguration configuration)
{
httpContextAccessor = _httpContextAccessor;
_configuration = configuration;
}
public ICurrentUser GetCurrentUser()
{
ICurrentUser currentUser = new CurrentUser();
if (httpContextAccessor.HttpContext == null) //cap
{
currentUser.UserCode = "cap";
currentUser.UserName = "cap";
}
else if (httpContextAccessor.HttpContext.User != null &&
httpContextAccessor.HttpContext.User.Identity.IsAuthenticated) //external
{
ClaimsPrincipal claimsPrincipal = httpContextAccessor.HttpContext.User;
var subject = claimsPrincipal.Claims.FirstOrDefault(w => w.Type == JwtClaimTypes.Subject);
var subjectRole = claimsPrincipal.Claims.FirstOrDefault(w => w.Type == JwtClaimTypes.Role);
currentUser = GetCurrentUserFromRedis(subject.Value, subjectRole.Value);
}
else //internal
{
currentUser.UserCode = "internal";
currentUser.UserName = "internal";
}
return currentUser;
}
private ICurrentUser GetCurrentUserFromRedis(string usercode, string tenantCode)
{
// var redisUserInfo = new CacheRedis(RedisDBType.User, _configuration).GetJSON<CurrentUserInfo>($"{tenantCode}:{usercode}");
return new CurrentUser();
// return redisUserInfo;
}
}
}
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
using System.Linq;
namespace Aurora.Infrastructure.Permission
{
public interface IFunctionPermission
{
string FunctionCode { get; set; }
string PermissionCode { get; set; }
}
}
\ No newline at end of file
using System;
namespace Aurora.Infrastructure.Response
{
public enum ErrorCodes
{
Success = 0,
Notfound = 400,
Error = 500,
NoPermession = 600,
}
}
using System;
namespace Aurora.Infrastructure.Response
{
public class ResponseModel<T>
{
ErrorCodes ErrorCode { get; set; }
T Data { get; set; }
public ResponseModel(T data)
{
Data = data;
ErrorCode = ErrorCodes.Success;
}
}
}
using System;
namespace Aurora.Infrastructure.Tenant
{
public interface ICurrentTenant
{
string TenantCode { get; set; }
}
}
using System;
namespace Aurora.Infrastructure.Tenant
{
public interface ICurrentTenantProvider
{
ICurrentTenant GetCurrentTenant();
}
}
using System;
using Aurora.Infrastructure.Permission;
using System.Collections.Generic;
namespace Aurora.Infrastructure.User
{
public interface ICurrentUser
{
/// <summary>
/// 用户登录用户Code
/// </summary>
string UserCode { get; set; }
/// <summary>
/// 用户名称
/// </summary>
string UserName { get; set; }
/// <summary>
/// 用户名 编码
/// </summary>
// string NameAndCode { get { return $"{CurrentUserName} {CurrentUserCode}"; } }
/// <summary>
/// 角色Code
/// </summary>
string RoleCode { get; set; }
/// <summary>
/// 角色Name
/// </summary>
string RoleName { get; set; }
List<IFunctionPermission> RolePermission { get; set; }
}
}
using System;
namespace Aurora.Infrastructure.User
{
public interface ICurrentUserProvider
{
ICurrentUser GetCurrentUser();
}
}
......@@ -5,11 +5,17 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Automapper" Version="10.1.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.6" />
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.22" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Aurora.Core.IService\Aurora.Core.IService.csproj" />
<ProjectReference Include="..\Aurora.Core.EntityFramework\Aurora.Core.EntityFramework.csproj" />
<ProjectReference Include="..\Aurora.Core.Service\Aurora.Core.Service.csproj" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aurora.Core.IService;
using Aurora.Core.IService.Dto;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Aurora.Core.Api.Controllers
{
[ApiController]
[Route("[controller]/[action]")]
public class CategoryController : ControllerBase
{
private readonly ILogger<CategoryController> _logger;
private readonly ICategoryService _categoryService;
public CategoryController(ILogger<CategoryController> logger,
ICategoryService categoryService)
{
_logger = logger;
_categoryService = categoryService;
}
[HttpGet]
/// <summary>
/// get cateories list
/// </summary>
/// <returns></returns>
public async Task<IActionResult> GetList()
{
var res = await _categoryService.GetList();
return Ok();
}
[HttpGet]
/// <summary>
/// get cateory by id
/// </summary>
/// <returns></returns>
public async Task<IActionResult> GetById(int id)
{
var res = await _categoryService.GetById(id);
return Ok();
}
[HttpPost]
/// <summary>
/// get cateory by id
/// </summary>
/// <returns></returns>
public async Task<IActionResult> Add(CategoryDto model)
{
var res = await _categoryService.Add(model);
return Ok();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Aurora.Core.Api.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]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
using System;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Aurora.Core.EntityFramework;
using Microsoft.EntityFrameworkCore;
using Aurora.Core.Service;
using Aurora.Core.IService;
using Aurora.Infrastructure.Tenant;
using Aurora.Infrastructure.User;
using Aurora.Common.User;
using Aurora.Common.Tenant;
using Microsoft.AspNetCore.Http;
namespace Aurora.Core.Api
{
public static class CoreApiModule
{
public static IServiceCollection AddCoreApiModule(this IServiceCollection services, IConfiguration configuration)
{
if (services == null)
{
throw new ArgumentNullException("services");
}
services.AddAutoMapper(Assembly.Load("Aurora.Core.Service"));
//注入请求上下文
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<ICurrentUserProvider, CurrentUserProvider>();
services.AddScoped<ICurrentTenantProvider, CurrentTenantProvider>();
services.AddDbContext<ApplicationDbContext>(option =>
option.UseMySQL(configuration["ConnectionStrings:MySql"]));
services.AddDbContext<ApplicationReadonlyDbContext>(option =>
option.UseMySQL(configuration["ReadOnlyConnectionStrings:MySql"]));
services.AddTransient<ICategoryService, CategoryService>();
// var RFCOptions = services.BuildServiceProvider().GetService<IOptions<SAPRFCSettings>>();
// //注入RFC链接
// services.AddSingleton(p =>
// new RfcConnection(builder => builder
// .UseConnectionHost(RFCOptions.Value.HostName)
// .UseLogonUserName(RFCOptions.Value.UserName)
// .UseLogonPassword(RFCOptions.Value.Password)
// .UseLogonClient(RFCOptions.Value.Client)
// .UseLogonLanguage(RFCOptions.Value.LogonLanguage)
// .UseSystemNumber(RFCOptions.Value.SystemNumber)
// .UseSapRouter(RFCOptions.Value.SapRouter))
// );
// services.AddSingleton<MMGoodsBomClient, MMGoodsBomClient>();
// services.AddSingleton<MMGoodsClient, MMGoodsClient>();
// services.AddSingleton<MMImporrPostDataClient, MMImporrPostDataClient>();
// services.AddSingleton<MMPOClient, MMPOClient>();
// services.AddSingleton<SDExporrPostDataClient, SDExporrPostDataClient>();
// services.AddSingleton<SDSOClient, SDSOClient>();
return services;
}
}
}
......@@ -22,7 +22,7 @@
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
......@@ -11,6 +12,9 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System.IO;
using Aurora.Core.EntityFramework;
using Microsoft.EntityFrameworkCore;
namespace Aurora.Core.Api
{
......@@ -32,6 +36,9 @@ namespace Aurora.Core.Api
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Aurora.Core.Api", Version = "v1" });
});
services.AddCoreApiModule(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
......
using System;
namespace Aurora.Core.Api
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}
......@@ -5,5 +5,19 @@
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"Enable": "MySql",
"MySql": "Server=127.0.0.1; Port=3380;User Id=root;Password=123456;Database=exam_practice;Allow User Variables=True",
"SqlServer": "Data Source=192.168.1.139;Initial Catalog=PTS2;User ID=sa;Password=;Encrypt=False;TrustServerCertificate=False;Pooling=true;max Pool Size=50;min Pool Size=1;MultipleActiveResultSets=True",
"PostgreSql": "Server=localhost;Database=Simon_blog;User ID=xxxxxx;Password=666",
"Sqlite": "Data Source=D:/xxx.db;"
},
"ReadOnlyConnectionStrings": {
"Enable": "MySql",
"MySql": "Server=127.0.0.1; Port=3381;User Id=root;Password=123456;Database=exam_practice;Allow User Variables=True",
"SqlServer": "Data Source=192.168.1.139;Initial Catalog=PTS2;User ID=sa;Password=;Encrypt=False;TrustServerCertificate=False;Pooling=true;max Pool Size=50;min Pool Size=1;MultipleActiveResultSets=True",
"PostgreSql": "Server=localhost;Database=Simon_blog;User ID=xxxxxx;Password=666",
"Sqlite": "Data Source=D:/xxx.db;"
}
}
}
\ No newline at end of file
......@@ -6,5 +6,12 @@
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
"AllowedHosts": "*",
"ConnectionStrings": {
"Enable": "MySql",
"MySql": "Server=xxxxxx; Port=3306;User Id=root;Password=xxxxx;Database=xxx;Allow User Variables=True",
"SqlServer": "Data Source=192.168.1.139;Initial Catalog=PTS2;User ID=sa;Password=;Encrypt=False;TrustServerCertificate=False;Pooling=true;max Pool Size=50;min Pool Size=1;MultipleActiveResultSets=True",
"PostgreSql": "Server=localhost;Database=Simon_blog;User ID=xxxxxx;Password=666",
"Sqlite": "Data Source=D:/xxx.db;"
}
}
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\..\..\Aurora.Common\Aurora.Common.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Automapper" Version="10.1.1" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
......
using System;
using Aurora.Core.Domain.Entities;
using Aurora.Core.Domain.Response;
namespace Aurora.Core.Domain.xxx
{
public class CategoryProfile : Profile
{
protected override void Configure()
{
CreateMap<CategoryDto, Category>();
}
}
}
using System;
using Aurora.Core.Domain.Entities;
using Aurora.Core.Domain.Response;
namespace Aurora.Core.Domain.xxx
{
public class CategoryProfile : Profile
{
protected override void Configure()
{
CreateMap<CategoryDto, Category>();
}
}
}
using System;
using Aurora.Core.Domain.Entities;
using Aurora.Core.Domain.Response;
namespace Aurora.Core.Domain.AutomapperProfiles
{
public class CategoryProfile : Profile
{
protected override void Configure()
{
CreateMap<CategoryDto, Category>();
}
}
}
using System;
namespace Aurora.Core.Domain
{
public class Class1
{
}
}
using System;
using Aurora.Common.Entities;
namespace Aurora.Core.Domain.Entities
{
public class Category : TenantEntityBase
{
public string CategoryName { get; set; }
public string Remark { get; set; }
}
}
using System;
namespace Aurora.Core.Domain.Response
{
public class CategoryDto
{
}
}
using System;
namespace Aurora.Core.Domain.xxx
{
public class xxx
{
}
}
......@@ -16,49 +16,12 @@ using Microsoft.EntityFrameworkCore;
namespace Aurora.Core.EntityFramework
{
public class ApplicationDbContext : DbContext
public class ApplicationDbContext : ApplicationReadonlyDbContext
{
public static string ConnectionString { get; set; }
private readonly ICurrentUser currentUser;
private readonly ICurrentTenant currentTenant;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options,
public ApplicationDbContext(DbContextOptions<ApplicationReadonlyDbContext> options,
ICurrentUserProvider currentUserProvider,
ICurrentTenantProvider currentTenantProvider) : base(options)
ICurrentTenantProvider currentTenantProvider) : base(options,currentUserProvider,currentTenantProvider)
{
currentUser = currentUserProvider.GetCurrentUser();
currentTenant = currentTenantProvider.GetCurrentTenant();
}
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
//多租户过滤
foreach (var type in GetBaseEntityTypes())
{
var method = SetGlobalQueryMethod.MakeGenericMethod(type);
method.Invoke(this, new object[] { builder });
}
builder.Entity<Category>().HasKey(t => new { t.TenantCode });
// builder.Entity<Category>().HasIndex(p => p.TenantCode);
base.OnModelCreating(builder);
}
private static IList<Type> _baseEntityTypesCache;
private static IList<Type> GetBaseEntityTypes()
{
if (_baseEntityTypesCache != null)
return _baseEntityTypesCache.ToList();
_baseEntityTypesCache = (from t in typeof(TenantEntityBase).GetTypeInfo().Assembly.DefinedTypes
where t.BaseType == typeof(TenantEntityBase)
select t.AsType()).ToList();
return _baseEntityTypesCache;
}
public override int SaveChanges()
......@@ -102,13 +65,5 @@ namespace Aurora.Core.EntityFramework
}
this.ChangeTracker.DetectChanges();
}
static readonly MethodInfo SetGlobalQueryMethod = typeof(ApplicationDbContext).GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Single(t => t.IsGenericMethod && t.Name == "SetGlobalQuery");
public void SetGlobalQuery<T>(ModelBuilder builder) where T : TenantEntityBase
{
builder.Entity<T>().HasQueryFilter(e => e.TenantCode == currentTenant.TenantCode);
}
}
}
\ No newline at end of file
......@@ -16,13 +16,12 @@ using Microsoft.EntityFrameworkCore;
namespace Aurora.Core.EntityFramework
{
public class ApplicationDbContext : DbContext
public class ApplicationReadonlyDbContext : DbContext
{
public static string ConnectionString { get; set; }
private readonly ICurrentUser currentUser;
private readonly ICurrentTenant currentTenant;
protected readonly ICurrentUser currentUser;
protected readonly ICurrentTenant currentTenant;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options,
public ApplicationReadonlyDbContext(DbContextOptions<ApplicationReadonlyDbContext> options,
ICurrentUserProvider currentUserProvider,
ICurrentTenantProvider currentTenantProvider) : base(options)
{
......@@ -60,50 +59,7 @@ namespace Aurora.Core.EntityFramework
select t.AsType()).ToList();
return _baseEntityTypesCache;
}
public override int SaveChanges()
{
UpdateCommonFileds();
return base.SaveChanges();
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
UpdateCommonFileds();
return await base.SaveChangesAsync(cancellationToken);
}
private void UpdateCommonFileds()
{
var nowTime = DateTime.Now;
if (string.IsNullOrEmpty(currentUser.UserName))
{
var tcode = currentTenant.TenantCode;
}
foreach (var entry in this.ChangeTracker.Entries<TenantEntityBase>().Where(x => x.State == EntityState.Added || x.State == EntityState.Modified))
{
var entity = entry.Entity;
switch (entry.State)
{
case EntityState.Added:
if (entity.TenantCode == "")
entity.TenantCode = currentTenant.TenantCode;
entity.CreateTime = nowTime;
entity.CreateUserName = currentUser.UserName;
break;
case EntityState.Modified:
entity.ModifyTime = nowTime;
entity.ModifyUserName = currentUser.UserName;
break;
}
}
this.ChangeTracker.DetectChanges();
}
static readonly MethodInfo SetGlobalQueryMethod = typeof(ApplicationDbContext).GetMethods(BindingFlags.Public | BindingFlags.Instance)
protected static readonly MethodInfo SetGlobalQueryMethod = typeof(ApplicationDbContext).GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Single(t => t.IsGenericMethod && t.Name == "SetGlobalQuery");
public void SetGlobalQuery<T>(ModelBuilder builder) where T : TenantEntityBase
......
......@@ -2,13 +2,14 @@
<ItemGroup>
<ProjectReference Include="..\Aurora.Core.Domain\Aurora.Core.Domain.csproj" />
<ProjectReference Include="..\..\..\Aurora.Common\Aurora.Common.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="EntityFrameWork" Version="6.4.4" />
<PackageReference Include="SqlSugarCore" Version="5.0.2.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.6" />
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.22" />
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="5.0.0" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
......
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Aurora.Core.Domain\Aurora.Core.Domain.csproj" />
<ProjectReference Include="..\..\..\Aurora.Infrastructure\Aurora.Infrastructure.csproj" />
</ItemGroup>
<PropertyGroup>
......
using System;
namespace Aurora.Core.IService
{
public class Class1
{
}
}
using System;
using Aurora.Core.Domain.Entities;
namespace Aurora.Core.Domain.Dto
namespace Aurora.Core.IService.Dto
{
public class CategoryDto : Category
public class CategoryDto
{
public string CategoryName { get; set; }
public string Remark { get; set; }
public string TenantCode { get; set; }
public int Id { get; set; }
public DateTimeOffset CreateTime { get; set; }
public string CreateUserName { get; set; }
public DateTimeOffset ModifyTime { get; set; }
public string ModifyUserName { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Aurora.Core.IService.Dto;
using Aurora.Infrastructure.Response;
namespace Aurora.Core.IService
{
public class ICategoryService
public interface ICategoryService
{
Task<ResponseModel<CategoryDto>> GetById(int id);
Task<ResponseModel<List<CategoryDto>>> GetList();
Task<ResponseModel<CategoryDto>> Add(CategoryDto model);
}
}
namespace Aurora.Core.Repositories.EntityFramework
{
public class ApplicationDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=Test",
providerOptions => { providerOptions.EnableRetryOnFailure(); });
}
}
}
\ No newline at end of file
......@@ -2,8 +2,16 @@
<ItemGroup>
<ProjectReference Include="..\Aurora.Core.IService\Aurora.Core.IService.csproj" />
<ProjectReference Include="..\..\..\Aurora.Infrastructure\Aurora.Infrastructure.csproj" />
<ProjectReference Include="..\Aurora.Core.EntityFramework\Aurora.Core.EntityFramework.csproj" />
<ProjectReference Include="..\..\..\Aurora.Infrastructure\Aurora.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Automapper" Version="10.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.6" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
......
using System;
using Aurora.Core.Domain.Entities;
using Aurora.Core.IService.Dto;
using AutoMapper;
namespace Aurora.Core.Service.AutomapperProfiles
{
public class CategoryProfile : Profile
{
//Source->Destination
// CreateMap<Source, Destination>();
// //Source->Destination2
// CreateMap<Source, Destination2>().ForMember(d => d.AnotherValue2, opt =>
// {
// opt.MapFrom(s => s.AnotherValue);
// });
public CategoryProfile()
{
CreateMap<Category, CategoryDto>();
CreateMap<CategoryDto, Category>();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aurora.Core.Domain.Entities;
using Aurora.Core.EntityFramework;
using Aurora.Core.IService;
using Aurora.Core.IService.Dto;
using Aurora.Infrastructure.Response;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
namespace Aurora.Core.Service
{
public class Class1
public class CategoryService : ICategoryService
{
private readonly ApplicationDbContext _dbContext;
private readonly ApplicationReadonlyDbContext _readonlyDbContext;
private readonly IMapper _mapper;
public CategoryService(ApplicationDbContext dbContext,
ApplicationReadonlyDbContext readonlyDbContext,
IMapper mapper)
{
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
_dbContext = dbContext;
_readonlyDbContext = readonlyDbContext;
}
public async Task<ResponseModel<List<CategoryDto>>> GetList()
{
var list = await _readonlyDbContext.Categories.ToListAsync();
var dtoList = _mapper.Map<List<CategoryDto>>(list);
var res = new ResponseModel<List<CategoryDto>>(dtoList);
return res;
}
public async Task<ResponseModel<CategoryDto>> GetById(int id)
{
var entity = await _readonlyDbContext.Categories.FirstOrDefaultAsync(m => m.Id == id);
var dto = _mapper.Map<CategoryDto>(entity);
var res = new ResponseModel<CategoryDto>(dto);
return res;
}
public async Task<ResponseModel<CategoryDto>> Add(CategoryDto model)
{
var entity = _mapper.Map<Category>(model);
_dbContext.Categories.Add(entity);
var num = await _dbContext.SaveChangesAsync();
var dto = _mapper.Map<CategoryDto>(entity);
var res = new ResponseModel<CategoryDto>(dto);
return res;
}
}
}
using System;
namespace Aurora.Core.Service
{
public class Class1
{
}
}
......@@ -21,10 +21,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aurora.Core.Domain", "Auror
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aurora.Core.IService", "Aurora.Micorservices\Aurora.Core\Aurora.Core.IService\Aurora.Core.IService.csproj", "{D4270B1E-D5DD-40D8-9281-54E2EBD38FB7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aurora.Core.Repositories", "Aurora.Micorservices\Aurora.Core\Aurora.Core.Repositories\Aurora.Core.Repositories.csproj", "{8E22664E-C22C-46E0-B970-056C24BEC66F}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aurora.Core.EntityFramework", "Aurora.Micorservices\Aurora.Core\Aurora.Core.EntityFramework\Aurora.Core.EntityFramework.csproj", "{8E22664E-C22C-46E0-B970-056C24BEC66F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aurora.Core.Service", "Aurora.Micorservices\Aurora.Core\Aurora.Core.Service\Aurora.Core.Service.csproj", "{E500647A-0385-49BF-BE01-3942C8C554A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aurora.Infrastructure", "Aurora.Infrastructure\Aurora.Infrastructure.csproj", "{46336F7C-61B1-481B-9860-1868249667B3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aurora.Common", "Aurora.Common\Aurora.Common.csproj", "{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -158,6 +162,30 @@ Global
{E500647A-0385-49BF-BE01-3942C8C554A9}.Release|x64.Build.0 = Release|Any CPU
{E500647A-0385-49BF-BE01-3942C8C554A9}.Release|x86.ActiveCfg = Release|Any CPU
{E500647A-0385-49BF-BE01-3942C8C554A9}.Release|x86.Build.0 = Release|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Debug|x64.ActiveCfg = Debug|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Debug|x64.Build.0 = Debug|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Debug|x86.ActiveCfg = Debug|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Debug|x86.Build.0 = Debug|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Release|Any CPU.Build.0 = Release|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Release|x64.ActiveCfg = Release|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Release|x64.Build.0 = Release|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Release|x86.ActiveCfg = Release|Any CPU
{46336F7C-61B1-481B-9860-1868249667B3}.Release|x86.Build.0 = Release|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Debug|x64.ActiveCfg = Debug|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Debug|x64.Build.0 = Debug|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Debug|x86.ActiveCfg = Debug|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Debug|x86.Build.0 = Debug|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Release|Any CPU.Build.0 = Release|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Release|x64.ActiveCfg = Release|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Release|x64.Build.0 = Release|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Release|x86.ActiveCfg = Release|Any CPU
{399C1F2A-FE91-4FA8-B1D4-5E077689EED4}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{DE864DFA-7032-4A52-9B73-7DA794FAE2EA} = {584A022C-ACAE-47E9-9D53-55FF40DC664D}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册