MyDbContext.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using Microsoft.EntityFrameworkCore;
  2. using AmrControl.DB.Models;
  3. using System.Linq.Expressions;
  4. using AmrControl.DB.Model;
  5. namespace AmrControl.DB
  6. {
  7. /// <summary>
  8. /// 数据库上下文配置
  9. /// </summary>
  10. public class MyDbContext: DbContext
  11. {
  12. /// <summary>
  13. /// 连接字符串
  14. /// </summary>
  15. private readonly string connStr;
  16. public MyDbContext(string connStr) :base()
  17. //public MyDbContext() :base()
  18. {
  19. this.connStr = connStr;
  20. //this.connStr = "server=localhost;user=mysqltest;database=ms_jgr;port=3306;password=test1234;Charset=utf8;Pooling=true";
  21. }
  22. /// <summary>
  23. /// 构造函数
  24. /// </summary>
  25. /// <param name="options"></param>
  26. #pragma warning disable CS8618 // 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑声明为可以为 null。
  27. public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
  28. #pragma warning restore CS8618 // 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑声明为可以为 null。
  29. {
  30. }
  31. /// <summary>
  32. ///
  33. /// 构造实体
  34. /// </summary>
  35. /// <param name="modelBuilder"></param>
  36. protected override void OnModelCreating(ModelBuilder modelBuilder)
  37. {
  38. //这条语句表示默认从本DLL中检索定义好的模型并创建对应的表,如果不这样做,那就需要在DbContext中定义所有模型并在这个函数中声明模型结构
  39. modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyDbContext).Assembly);
  40. base.OnModelCreating(modelBuilder);
  41. }
  42. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  43. {
  44. base.OnConfiguring(optionsBuilder);
  45. //如果用mysql,则开启下面的语句
  46. //if (this.connStr != null)
  47. //{
  48. // optionsBuilder.UseMySql(connStr, ServerVersion.AutoDetect(connStr));
  49. //}
  50. //如果用sqlite,则开启下面的语句
  51. if (this.connStr != null)
  52. {
  53. optionsBuilder.UseSqlite(connStr);
  54. }
  55. }
  56. /// <summary>
  57. /// 用户模型
  58. /// </summary>
  59. #pragma warning disable IDE1006 // 命名样式
  60. public DbSet<UserModel> userDb { get; set; }
  61. public DbSet<Log> logs { get; set; }
  62. public DbSet<AppConfig> appConfigs { get; set; }
  63. public DbSet<Models.JGR> jgrs { get; set; }
  64. public DbSet<Models.Charger> chargers { get; set; }
  65. public DbSet<Models.Station> stations { get; set; }
  66. public DbSet<Models.Material> materials { get; set; }
  67. public DbSet<Models.Storage> storages { get; set; }
  68. public DbSet<Models.IssueNote> issuenotes { get; set; }
  69. #pragma warning restore IDE1006 // 命名样式
  70. }
  71. }