Seamus 7 months ago
parent
commit
cec50999ed

+ 4 - 0
ERP.Application/ERP.Application.csproj

@@ -12,4 +12,8 @@
     <ProjectReference Include="..\ERP.Core\ERP.Core.csproj" />
   </ItemGroup>
 
+  <ItemGroup>
+    <Folder Include="Context\" />
+  </ItemGroup>
+
 </Project>

+ 7 - 7
ERP.Application/Program.cs

@@ -9,14 +9,14 @@ namespace ERP
         {
             Console.Title = "ERP.Application";
             Console.WriteLine($@"
-                                  _____ ____  ____    ____  ____  ____  _     _  ____  ____  _____  _  ____  _     
-                                /  __//  __\/  __\  /  _ \/  __\/  __\/ \   / \/   _\/  _ \/__ __\/ \/  _ \/ \  /|
-                                |  \  |  \/||  \/|  | / \||  \/||  \/|| |   | ||  /  | / \|  / \  | || / \|| |\ ||
-                                |  /_ |    /|  __/__| |-|||  __/|  __/| |_/\| ||  \_ | |-||  | |  | || \_/|| | \||
-                                \____\\_/\_\\_/   \/\_/ \|\_/   \_/   \____/\_/\____/\_/ \|  \_/  \_/\____/\_/  \|
+                      _____ ____  ____    ____  ____  ____  _     _  ____  ____  _____  _  ____  _     
+                     /  __//  __\/  __\  /  _ \/  __\/  __\/ \   / \/   _\/  _ \/__ __\/ \/  _ \/ \  /|
+                     |  \  |  \/||  \/|  | / \||  \/||  \/|| |   | ||  /  | / \|  / \  | || / \|| |\ ||
+                     |  /_ |    /|  __/__| |-|||  __/|  __/| |_/\| ||  \_ | |-||  | |  | || \_/|| | \||
+                     \____\\_/\_\\_/   \/\_/ \|\_/   \_/   \____/\_/\____/\_/ \|  \_/  \_/\____/\_/  \|
                                                                                   
-                        -------------------------------------------------------------------------------------
-                                      Start Time:  {DateTime.Now.ToString(DateTimeConstant.Date_Long)}");
+               ----------------------------------------------------------------------------------------------
+                                 Start Time:  {DateTime.Now.ToString(DateTimeConstant.Date_Long)}");
 
             var app = WebApplication
                 .CreateBuilder(args)

+ 19 - 5
ERP.Application/appsettings.Development.json

@@ -1,8 +1,22 @@
 {
-  "Logging": {
-    "LogLevel": {
-      "Default": "Information",
-      "Microsoft.AspNetCore": "Warning"
-    }
+  "DBConfig": {
+    "ConnectionConfigs": [
+      {
+        "DbType": 0,
+        "ConnectionString": "server=8.222.216.184;Database=erp;Uid=root;Pwd=zyh@0728;"
+      }
+    ]
+  },
+  " ConnectionStrings": {
+    "CoreDBContext": "server=127.0.0.1;user id=root;database= ;password= ", //my sql
+    "CoreDBContext2": "server=127.0.0.1;user id=root;database= ;password= ", //my sql
+    "CoreDBContext3": "server=127.0.0.1;user id=root;database= ;password= ", //my sql
+    "CoreDBContext4": "server=127.0.0.1;user id=root;database= ;password= ", //my sql
+    "CoreDBContext5": "server=127.0.0.1;user id=root;database= ;password= " //my sql
+  },
+  "Redis": {
+    "Host": "localhost",
+    "Port": "6379",
+    "Password": "PSSRND20190710"
   }
 }

+ 4 - 3
ERP.Core/Application.cs

@@ -39,7 +39,7 @@ namespace ERP.Core
             // 缓存注册
             builder.Services.AddCache(redisConfig);
             // EntityFrameworkCore
-            //builder.Services.AddSqlSugar(dbConfig);
+            builder.Services.AddEntityFrameworkMySql();
             //  跨域
             builder.Services.AddCorsAccessor();
             // Todo 任务队列
@@ -48,6 +48,7 @@ namespace ERP.Core
             // Todo 添加MiniProfiler 性能分析
 
             // Swagger
+            builder.Services.AddSwaggerGen();
             //builder.Services.AddSwagger();
 
             // 校验异常拦截
@@ -90,8 +91,8 @@ namespace ERP.Core
             app.UseHttpsRedirection();
             //app.UseI18N();
 
-            //app.UseSwagger();
-            //app.UseSwaggerUI();
+            app.UseSwagger();
+            app.UseSwaggerUI();
 
             app.UseRouting();
             app.UseEndpoints(endpoints =>

+ 43 - 0
ERP.Core/Context/CoreDbContext.cs

@@ -0,0 +1,43 @@
+using ERP.Core.Entity;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Configuration;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ERP.Core.Context
+{
+    public class CoreDbContext : DbContext
+    {
+        private readonly IConfiguration _configuration;
+
+        public CoreDbContext(IConfiguration configuration)
+        {
+            this._configuration = configuration;
+        }
+
+        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
+        {
+            // 可扩展为多租户,从当前请求头拿租户Id,根据租户Id获取对应数据库配置名,替换
+            string connect = _configuration.GetConnectionString(GetType().Name)!;
+
+            optionsBuilder.UseMySql(connect,new MySqlServerVersion(new Version(8,0,26)));
+            base.OnConfiguring(optionsBuilder);
+        }
+
+        /// <summary>
+        /// 配置模型关系
+        /// </summary>
+        /// <param name="modelBuilder"></param>
+        protected override void OnModelCreating(ModelBuilder modelBuilder)
+        {
+
+        }
+
+        public virtual DbSet<SysUser> SysUsers { get; set; }
+
+
+    }
+}

+ 3 - 1
ERP.Core/Controller/AuthController.cs

@@ -26,9 +26,11 @@ namespace ERP.Core.Controller
         //[SwaggerOperation(Description = "登录接口", Summary = "Login")]
         public async Task<IActionResult> LoginAsync([FromBody] LoginBody form)
         {
+            var m = GetType().Name;
+
             var securityConfig = _configuration.GetSection(FrameworkConstant.SecurityConfig).Get<SecurityConfig>() ?? new SecurityConfig();
 
-            var loginUser = await _authService.GetLoginUser(securityConfig, form.LoginName, form.Password);
+            var loginUser = _authService.GetLoginUser(securityConfig, form.LoginName, form.Password);
 
             //var jwtToken = LoginHelper.LoginByDevice(loginUser, securityConfig, DeviceEnum.Web);
 

+ 22 - 1
ERP.Core/Controller/SysUserController.cs

@@ -1,8 +1,29 @@
-using ERP.Framework.WebApi;
+using ERP.Core.Service;
+using ERP.Framework.WebApi;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Configuration;
 
 namespace ERP.Core.Controller
 {
+    [Route("/sys-user")]
     public class SysUserController : BaseController
     {
+        private readonly IConfiguration _configuration;
+        private readonly AuthService _authService;
+
+        public SysUserController(IConfiguration configuration, AuthService authService)
+        {
+            _configuration = configuration;
+            _authService = authService;
+        }
+
+        [HttpGet]
+        public void Test()
+        {
+            var m = GetType().Name;
+
+            var c = "";
+
+        }
     }
 }

+ 6 - 3
ERP.Core/Repository/SysUserRepository.cs

@@ -1,4 +1,5 @@
-using ERP.Core.Dto;
+using ERP.Core.Context;
+using ERP.Core.Dto;
 using ERP.Core.Entity;
 using ERP.Framework.WebApi;
 using System;
@@ -9,8 +10,10 @@ using System.Threading.Tasks;
 
 namespace ERP.Core.Repository
 {
-    public class SysUserRepository 
+    public class SysUserRepository : BaseRepository<SysUser, CoreDbContext>
     {
-   
+        public SysUserRepository(CoreDbContext context) : base(context)
+        {
+        }
     }
 }

+ 9 - 9
ERP.Core/Service/AuthService.cs

@@ -25,27 +25,27 @@ namespace ERP.Core.Service
         /// <summary>
         /// 获取登录用户
         /// </summary>
-        /// <param name="securityConfig">设置</param>
+        /// <param name="securityConfig">设置</param>r
         /// <param name="loginName">用户名</param>
         /// <param name="password">密码</param>
         /// <param name="deviceKey">设备唯一值</param>
         /// <returns></returns>
         /// <exception cref="Exception"></exception>
-        public async Task<LoginUser> GetLoginUser(
+        public  LoginUser GetLoginUser(
             SecurityConfig securityConfig
             , string loginName
             , string password)
         {
-            //var user = await _sysUserRepository.SelectByUserName(loginName);
+            var user = _sysUserRepository.FirstOrDefault(t => t.UserName == loginName);
 
-            //if (user == null)
-            //{
-            //    throw new Exception(string.Format(_localizer["User.NotExist"], loginName));
-            //}
+            if (user == null)
+            {
+                throw new Exception(string.Format(_localizer["User.NotExist"], loginName));
+            }
 
-            //CheckUserStatus(user);
+            CheckUserStatus(user);
 
-            //CheckLogin(securityConfig, password, user);
+            CheckLogin(securityConfig, password, user);
 
             return new LoginUser();
         }

+ 2 - 2
ERP.Core/Service/SysUserService.cs

@@ -18,11 +18,11 @@ namespace ERP.Core.Service
 
         public async Task<LoginUser> GetUserInfo(string loginName)
         {
-            //var user = await SysUserRepository.SelectByUserName(loginName);
+            var user = SysUserRepository.FirstOrDefault(t => t.UserName == loginName);
 
             //if (user == null)
             //{
-            //    //throw new Exception(new Status(StatusCode.Unknown, string.Format(_localizer["User.NotExist"], loginName)));
+            //    throw new Exception(string.Format(_localizer["User.NotExist"], loginName)));
             //}
 
             //CheckUserStatus(user);

+ 71 - 0
ERP.Framework/WebApi/BaseRepository.cs

@@ -0,0 +1,71 @@
+using Microsoft.EntityFrameworkCore;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace ERP.Framework.WebApi
+{
+    public class BaseRepository<T, TDbContext> where T : BaseEntity where TDbContext : DbContext
+    {
+        private TDbContext _context;
+
+        public BaseRepository(TDbContext context)
+        {
+            _context = context;
+        }
+
+        public T? FirstOrDefault(Expression<Func<T, bool>> exp = null)
+        {
+            return Filter(exp).FirstOrDefault();
+        }
+
+        public void Add(T entity)
+        {
+            _context.Set<T>().Add(entity);
+            Save();
+            _context.Entry(entity).State = EntityState.Detached;
+        }
+
+        public void Save()
+        {
+            try
+            {
+                var entities = _context.ChangeTracker.Entries()
+                    .Where(e => e.State == EntityState.Added
+                                || e.State == EntityState.Modified)
+                    .Select(e => e.Entity);
+
+                foreach (var entity in entities)
+                {
+                    var validationContext = new ValidationContext(entity);
+                    Validator.ValidateObject(entity, validationContext, validateAllProperties: true);
+                }
+
+                _context.SaveChanges();
+            }
+            catch (ValidationException exc)
+            {
+                // Todo 抛出异常
+                //Console.WriteLine($"{nameof(Save)} validation exception: {exc?.Message}");
+                //throw (exc.InnerException as Exception ?? exc);
+            }
+            catch (Exception ex) //DbUpdateException 
+            {
+                // Todo 抛出异常
+                //throw (ex.InnerException as Exception ?? ex);
+            }
+        }
+
+        private IQueryable<T> Filter(Expression<Func<T, bool>> exp)
+        {
+            var dbSet = _context.Set<T>().AsNoTracking().AsQueryable();
+            if (exp != null)
+                dbSet = dbSet.Where(exp);
+            return dbSet;
+        }
+    }
+}