DataContext.cs 2.74 KB
using FreeSql;
using HHECS.DAQHandle.Models;
using HHECS.EquipmentModel;

namespace HHECS.DAQHandle.DataAccess
{
    /// <summary>
    /// 数据库上下文
    /// </summary>
    /// <remarks>
    /// <para>参考文档:<a href="https://freesql.net/guide/db-context.html">https://freesql.net/guide/db-context.html</a></para>
    /// <para>注意:<see cref="DataContext"/> 对象多线程不安全</para>
    /// </remarks>
    public class DataContext : DbContext
    {
        public DbSet<Equipment> Equipment { get; set; } = null!;

        public DbSet<EquipmentType> EquipmentType { get; set; } = null!;

        public DbSet<EquipmentTypePropTemplate> EquipmentTypePropTemplate { get; set; } = null!;

        public DbSet<EquipmentProp> EquipmentProp { get; set; } = null!;

        public DbSet<EquipmentDataRecord> EquipmentDataRecord { get; set; } = null!;

        public DbSet<EquipmentAlarmRecord> EquipmentAlarmRecords { get; set; } = null!;

        public DbSet<EquipmentStatusRecordHistory> EquipmentStatusRecordHistorys { get; set; } = null!;
        public DbSet<EquipmentStatusRecord> EquipmentStatusRecords { get; set; } = null!;
        public DbSet<Project> Project { get; set; } = null!;
        public DbSet<WareHouse> WareHouse { get; set; } = null!;

        protected override void OnConfiguring(DbContextOptionsBuilder builder)
        {
            builder.UseFreeSql(GlobalVar.FreeSql);
        }

        protected override void OnModelCreating(ICodeFirst codefirst)
        {
            codefirst.Entity<Equipment>(eb =>
            {
                eb.ToTable($"daq_equipment");

                eb.HasIndex(x => x.Code).IsUnique();
            });

            codefirst.Entity<EquipmentType>(eb =>
            {
                eb.ToTable("daq_equipment_type");
            });

            codefirst.Entity<EquipmentProp>(eb =>
            {
                eb.ToTable("daq_equipment_prop");
            });

            codefirst.Entity<EquipmentTypePropTemplate>(eb =>
            {
                eb.ToTable("daq_equipment_type_prop_template");
                eb.Property(p => p.PropType).HasColumnType("varchar(50)").Help().MapType(typeof(string));
                eb.Property(p => p.DataType).HasColumnType("varchar(50)").Help().MapType(typeof(string));
            });

            codefirst.Entity<Project>(eb =>
            {
                eb.ToTable("daq_project");
            });
            codefirst.Entity<WareHouse>(eb =>
            {
                eb.ToTable("daq_warehouse");
            });
            codefirst.SyncStructure<Equipment>();
            codefirst.SyncStructure<EquipmentType>();
            codefirst.SyncStructure<EquipmentProp>();
            codefirst.SyncStructure<EquipmentTypePropTemplate>();
        }
    }
}