CZDbContext.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using CZFW.Core;
  2. using CZFW.Core.Security;
  3. using CZFW.Framework.Model.Entity;
  4. using Microsoft.EntityFrameworkCore;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.Logging;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Text;
  13. using System.Threading;
  14. namespace CZFW.Framework.Model
  15. {
  16. public class CZDbContext : DbContext
  17. {
  18. //public CZDbContext(DbContextOptions options) : base(options)
  19. //{
  20. //}
  21. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  22. {
  23. //optionsBuilder.UseSqlServer(@"data Source=114.55.54.52,1433\CZDB;database=CZKJ_WLGL;user id =sa;pwd=CZKJczkj2016");
  24. //optionsBuilder.UseMySQL(DesEncrypt.Decrypt(ConfigHelper.GetValue<string>("ConnectionStrings:Development")));
  25. optionsBuilder.UseMySQL(ConfigHelper.GetValue<string>("ConnectionStrings:Development"));
  26. base.OnConfiguring(optionsBuilder);
  27. }
  28. protected override void OnModelCreating(ModelBuilder modelBuilder)
  29. {
  30. string path = Thread.GetDomain().BaseDirectory;
  31. CZHttpContext.Logger.LogError($"当前目录:{path}");
  32. var scanPath = ConfigHelper.Configs.GetValue<string>("EFScanPath");
  33. path = path + scanPath;
  34. CZHttpContext.Logger.LogError($"即将扫描路径:{path}");
  35. Assembly[] assemblies = new DirectoryInfo(path).GetFiles("CZ*.dll", SearchOption.AllDirectories)
  36. .Select(x => Assembly.LoadFrom(x.FullName)).ToArray();
  37. Type baseType = typeof(EntityBase);
  38. foreach (var assembly in assemblies)
  39. {
  40. IEnumerable<Type> entityTypes = assembly.GetTypes().Where(entityType => entityType.IsSubclassOf(baseType));
  41. foreach (var type in entityTypes)
  42. {
  43. modelBuilder.Entity(type);
  44. }
  45. }
  46. base.OnModelCreating(modelBuilder);
  47. }
  48. }
  49. }