using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Data.Common; #nullable disable namespace AsbCloudDb.Model { //Scaffold-DbContext "Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Model -DataAnnotations public partial class AsbCloudDbContext : DbContext, IAsbCloudDbContext { public virtual DbSet Clusters { get; set; } public virtual DbSet Companies { get; set; } public virtual DbSet DataSaubBases { get; set; } public virtual DbSet Deposits { get; set; } public virtual DbSet Users { get; set; } public virtual DbSet UserRoles { get; set; } public virtual DbSet Wells { get; set; } public virtual DbSet ReportProperties { get; set; } public virtual DbSet Files { get; set; } public virtual DbSet FileCategories { get; set; } public virtual DbSet Telemetries { get; set; } public virtual DbSet TelemetryEvents { get; set; } public virtual DbSet TelemetryMessages { get; set; } public virtual DbSet TelemetryUsers { get; set; } public virtual DbSet TelemetryOperations { get; set; } public virtual DbSet TelemetryAnalysis { get; set; } public virtual DbSet WellSections { get; set; } public virtual DbSet WellSectionTypes { get; set; } public virtual DbSet WellOperations { get; set; } public virtual DbSet WellTypes { get; set; } public virtual DbSet LastData { get; set; } //var options = new DbContextOptionsBuilder() // .UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True") // .Options; //var context = new AsbCloudDbContext(options); public AsbCloudDbContext(DbContextOptions options) : base(options) { Database.EnsureCreated(); } //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) //{ // if (!optionsBuilder.IsConfigured) // { // optionsBuilder.UseNpgsql(connectionString); // } //} protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasPostgresExtension("adminpack") .HasAnnotation("Relational:Collation", "Russian_Russia.1251"); modelBuilder.Entity(entity => { entity.HasOne(d => d.Deposit) .WithMany(p => p.Clusters) .HasForeignKey(d => d.IdDeposit) .HasConstraintName("t_cluster_t_deposit_id_fk"); }); modelBuilder.Entity(entity => { entity.HasOne(d => d.Telemetry) .WithMany(p => p.DataSaubBases) .HasForeignKey(d => d.IdTelemetry) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("t_data_saub_base_t_telemetry_id_fk"); }); modelBuilder.Entity(entity => { entity.HasOne(d => d.Telemetry) .WithMany(p => p.Messages) .HasForeignKey(d => d.IdTelemetry) .HasConstraintName("t_messages_t_telemetry_id_fk"); }); modelBuilder.Entity(entity => { entity.HasKey(nameof(TelemetryUser.IdTelemetry), nameof(TelemetryUser.IdUser)); entity.HasOne(d => d.Telemetry) .WithMany(p => p.Users) .HasForeignKey(d => d.IdTelemetry) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("t_telemetry_user_t_telemetry_id_fk"); }); modelBuilder.Entity(entity => { entity.HasOne(d => d.Telemetry) .WithMany(p => p.Analysis) .HasForeignKey(d => d.IdTelemetry) .HasConstraintName("t_analysis_t_telemetry_id_fk"); entity.HasOne(d => d.Operation) .WithMany(p => p.Analysis) .HasForeignKey(d => d.IdOperation) .OnDelete(DeleteBehavior.SetNull) .HasConstraintName("t_analysis_t_operation_id_fk"); }); modelBuilder.Entity(entity => { entity.HasKey(nameof(TelemetryEvent.IdTelemetry), nameof(TelemetryEvent.IdEvent)); entity.HasOne(d => d.Telemetry) .WithMany(p => p.Events) .HasForeignKey(d => d.IdTelemetry) .HasConstraintName("t_event_t_telemetry_id_fk"); }); modelBuilder.Entity(entity => { entity.HasOne(d => d.Company) .WithMany(p => p.Users) .HasForeignKey(d => d.IdCompany) .HasConstraintName("t_user_t_company_id_fk"); entity.HasIndex(d => d.Login) .IsUnique(); }); modelBuilder.Entity(entity => { entity.HasOne(d => d.Cluster) .WithMany(p => p.Wells) .HasForeignKey(d => d.IdCluster) .HasConstraintName("t_well_t_cluster_id_fk"); entity.HasOne(d => d.Telemetry) .WithOne(p => p.Well) .HasForeignKey(d => d.IdTelemetry) .HasConstraintName("t_well_t_telemetry_id_fk"); }); modelBuilder.Entity(entity => { entity.HasIndex(e => e.WellDepthPlan) .HasDatabaseName("IX_t_well_section_well_depth_plan"); }); modelBuilder.Entity(entity => { entity.HasKey(nameof(RelationCompanyWell.IdCompany), nameof(RelationCompanyWell.IdWell)); entity.HasOne(r => r.Well) .WithMany(w => w.RelationCompaniesWells) .HasForeignKey(r => r.IdWell) .HasConstraintName("t_relation_company_well_t_well_id_fk"); entity.HasOne(r => r.Company) .WithMany(w => w.RelationCompaniesWells) .HasForeignKey(r => r.IdCompany) .HasConstraintName("t_relation_company_well_t_company_id_fk"); }); modelBuilder.Entity(entity => { entity.HasIndex(d => d.WellDepth); entity.HasIndex(d => d.StartDate); }); FillData(modelBuilder); FillDemoData(modelBuilder); } private static void FillData(ModelBuilder modelBuilder) { modelBuilder.Entity(entity => { entity.HasData(new List{ new UserRole{ Id = 1, Caption = "Администратор", }, }); }); modelBuilder.Entity(entity => { entity.HasData(new List{ new User{ Id = 1, IdCompany = 1, IdRole = 1, Level = int.MaxValue, Login = "dev", PasswordHash = "Vlcj|4fa529103dde7ff72cfe76185f344d4aa87931f8e1b2044e8a7739947c3d18923464eaad93843e4f809c5e126d013072", // dev Name = "Разработчик", }, }); }); modelBuilder.Entity(entity => { entity.HasData(new List{ new Company{ Id = 1, Caption = "ООО \"АСБ\"", IdCompanyType = 3}, }); }); modelBuilder.Entity(entity => { entity.HasData(new List { // Автоматически опеределяемые операции new WellOperationCategory {Id = 1, Name = "Невозможно определить операцию", Code = 0}, new WellOperationCategory {Id = 2, Name = "Роторное бурение", Code = 0 }, new WellOperationCategory {Id = 3, Name = "Слайдирование", Code = 0 }, new WellOperationCategory {Id = 4, Name = "Подъем с проработкой", Code = 0 }, new WellOperationCategory {Id = 5, Name = "Спуск с проработкой", Code = 0 }, new WellOperationCategory {Id = 6, Name = "Подъем с промывкой", Code = 0 }, new WellOperationCategory {Id = 7, Name = "Спуск с промывкой", Code = 0 }, new WellOperationCategory {Id = 8, Name = "Спуск в скважину", Code = 0 }, new WellOperationCategory {Id = 9, Name = "Спуск с вращением", Code = 0 }, new WellOperationCategory {Id = 10, Name = "Подъем из скважины", Code = 0 }, new WellOperationCategory {Id = 11, Name = "Подъем с вращением", Code = 0 }, new WellOperationCategory {Id = 12, Name = "Промывка в покое", Code = 0 }, new WellOperationCategory {Id = 13, Name = "Промывка с вращением", Code = 0 }, new WellOperationCategory {Id = 14, Name = "Удержание в клиньях", Code = 0 }, new WellOperationCategory {Id = 15, Name = "Неподвижное состояние", Code = 0 }, new WellOperationCategory {Id = 16, Name = "Вращение без циркуляции", Code = 0 }, new WellOperationCategory {Id = 17, Name = "На поверхности", Code = 0 }, // Операции ручного ввода new WellOperationCategory {Id = 18, Name = "Бурение", Code = 0 }, new WellOperationCategory {Id = 19, Name = "Бурение в интервале", Code = 0 }, new WellOperationCategory {Id = 20, Name = "Бурение до глубины", Code = 0 }, new WellOperationCategory {Id = 21, Name = "Бурение под направление", Code = 0 }, new WellOperationCategory {Id = 22, Name = "ГИС (инклиметрия)", Code = 0 }, new WellOperationCategory {Id = 23, Name = "ГИС (инклинометрия)", Code = 0 }, new WellOperationCategory {Id = 24, Name = "ГФР - АМАК, АКЦ кондуктора", Code = 0 }, new WellOperationCategory {Id = 25, Name = "Демонтаж ПВО, Установка ФА", Code = 0 }, new WellOperationCategory {Id = 26, Name = "Оборудование устья", Code = 0 }, new WellOperationCategory {Id = 27, Name = "ОЗЦ", Code = 0 }, new WellOperationCategory {Id = 28, Name = "ГИС", Code = 0 }, new WellOperationCategory {Id = 29, Name = "Окончание цикла бурения", Code = 0 }, new WellOperationCategory {Id = 30, Name = "Опрессовка ПВО", Code = 0 }, new WellOperationCategory {Id = 31, Name = "Опресовка Ц.К.", Code = 0 }, new WellOperationCategory {Id = 32, Name = "Опрессовка ВЗД", Code = 0 }, new WellOperationCategory {Id = 33, Name = "Перевод скв на KCL", Code = 0 }, new WellOperationCategory {Id = 34, Name = "Перезапись гаммы", Code = 0 }, new WellOperationCategory {Id = 35, Name = "Перезапись ГК", Code = 0 }, new WellOperationCategory {Id = 36, Name = "Перетяжка тальканата", Code = 0 }, new WellOperationCategory {Id = 37, Name = "Подъем", Code = 0 }, new WellOperationCategory {Id = 38, Name = "Подъем ЛБТ", Code = 0 }, new WellOperationCategory {Id = 39, Name = "Подъем инструмента", Code = 0 }, new WellOperationCategory {Id = 40, Name = "ПР и Сборка КНБК", Code = 0 }, new WellOperationCategory {Id = 41, Name = "ПР к бурению и сборке КНБК", Code = 0 }, new WellOperationCategory {Id = 42, Name = "ПР к промывке", Code = 0 }, new WellOperationCategory {Id = 43, Name = "ПР к спуску кондуктора", Code = 0 }, new WellOperationCategory {Id = 44, Name = "ПР к спуску направления", Code = 0 }, new WellOperationCategory {Id = 45, Name = "ПР к спуску ОК", Code = 0 }, new WellOperationCategory {Id = 46, Name = "ПР к спуску ЭК-146", Code = 0 }, new WellOperationCategory {Id = 47, Name = "ПР к цементажу", Code = 0 }, new WellOperationCategory {Id = 48, Name = "ПР к цементированию кондуктора", Code = 0 }, new WellOperationCategory {Id = 49, Name = "ПР к цементированию направления", Code = 0 }, new WellOperationCategory {Id = 50, Name = "ПР к цементированию ЭК", Code = 0 }, new WellOperationCategory {Id = 51, Name = "ПР. Спуск направления", Code = 0 }, new WellOperationCategory {Id = 52, Name = "ПР. цементаж направления", Code = 0 }, new WellOperationCategory {Id = 53, Name = "Промывка", Code = 0 }, new WellOperationCategory {Id = 54, Name = "Промежуточная промывка", Code = 0 }, new WellOperationCategory {Id = 55, Name = "Промывка на забое", Code = 0 }, new WellOperationCategory {Id = 56, Name = "Промывка перед бурением", Code = 0 }, new WellOperationCategory {Id = 57, Name = "Промывка перед ГИС", Code = 0 }, new WellOperationCategory {Id = 58, Name = "Промывка перед подъемом", Code = 0 }, new WellOperationCategory {Id = 59, Name = "Промывка перед цементажем", Code = 0 }, new WellOperationCategory {Id = 60, Name = "Промывка перед цементированием", Code = 0 }, new WellOperationCategory {Id = 61, Name = "Промывка прокачка", Code = 0 }, new WellOperationCategory {Id = 62, Name = "Промывка с прокачкой", Code = 0 }, new WellOperationCategory {Id = 63, Name = "Разборка КНБК", Code = 0 }, new WellOperationCategory {Id = 64, Name = "Разбуривание тех.оснастки", Code = 0 }, new WellOperationCategory {Id = 65, Name = "Разбурка ЦКОДа", Code = 0 }, new WellOperationCategory {Id = 66, Name = "Ремонт наг.линии подпорного насоса", Code = 0 }, new WellOperationCategory {Id = 67, Name = "Ремонт наг.линии подпорного насоса", Code = 0 }, new WellOperationCategory {Id = 68, Name = "Сборка КНБК", Code = 0 }, new WellOperationCategory {Id = 69, Name = "Сборка роторной КНБК", Code = 0 }, new WellOperationCategory {Id = 70, Name = "Спуск инструмента", Code = 0 }, new WellOperationCategory {Id = 71, Name = "Спуск КНБК", Code = 0 }, new WellOperationCategory {Id = 72, Name = "Подъем КНБК", Code = 0 }, new WellOperationCategory {Id = 73, Name = "Спуск ЛБТ", Code = 0 }, new WellOperationCategory {Id = 74, Name = "Спуск ОК", Code = 0 }, new WellOperationCategory {Id = 75, Name = "Спуск ЭК", Code = 0 }, new WellOperationCategory {Id = 76, Name = "Тех СПО", Code = 0 }, new WellOperationCategory {Id = 77, Name = "Тех СПО-подъем", Code = 0 }, new WellOperationCategory {Id = 78, Name = "Тех СПО-спуск", Code = 0 }, new WellOperationCategory {Id = 79, Name = "ТО СВП", Code = 0 }, new WellOperationCategory {Id = 80, Name = "Цементаж", Code = 0 }, new WellOperationCategory {Id = 81, Name = "Цементаж кондуктора", Code = 0 }, new WellOperationCategory {Id = 82, Name = "Цементаж направления", Code = 0 }, new WellOperationCategory {Id = 83, Name = "Цементаж ЭК", Code = 0 }, new WellOperationCategory {Id = 84, Name = "Шаблонировка ствола", Code = 0 }, new WellOperationCategory {Id = 85, Name = "Cпуск направления", Code = 0 } }); }); modelBuilder.Entity(entity => { entity.HasData(new List { new FileCategory {Id = 1, Name = "Растворный сервис", ShortName = "fluidService"}, new FileCategory {Id = 2, Name = "Цементирование", ShortName = "cement"}, new FileCategory {Id = 3, Name = "ННБ", ShortName = "nnb"}, new FileCategory {Id = 4, Name = "ГТИ", ShortName = "gti"}, new FileCategory {Id = 5, Name = "Документы по скважине", ShortName = "wellDocuments"}, new FileCategory {Id = 6, Name = "Супервайзер", ShortName = "supervisor"}, new FileCategory {Id = 7, Name = "Мастер", ShortName = "master"}, new FileCategory {Id = 8, Name = "Последний замер бурового раствора ПЛАН", ShortName = "fluidPlanLastData"}, new FileCategory {Id = 9, Name = "Последний замер бурового раствора ФАКТ", ShortName = "fluidFactLastData"}, new FileCategory {Id = 10, Name = "Последние данные Шламограммы", ShortName = "mudLastData"}, new FileCategory {Id = 11, Name = "Последние данные ННБ", ShortName = "nnbLastData"}, new FileCategory {Id = 12, Name = "Рапорт", ShortName = "report"} }); }); modelBuilder.Entity(entity => { entity.HasData(new List{ new WellSectionType{ Id = 1, Caption = "Пилотный ствол"}, new WellSectionType{ Id = 2, Caption = "Направление"}, new WellSectionType{ Id = 3, Caption = "Кондуктор"}, new WellSectionType{ Id = 4, Caption = "Эксплуатационная колонна"}, new WellSectionType{ Id = 5, Caption = "Транспортный ствол"}, new WellSectionType{ Id = 6, Caption = "Хвостовик"}, }); }); } private static void FillDemoData(ModelBuilder modelBuilder) { modelBuilder.Entity(entity => { entity.HasData(new List{ new CompanyType{ Id = 1, Caption = "Недрапользователь", }, new CompanyType{ Id = 2, Caption = "Буровой подрядчик", }, new CompanyType{ Id = 3, Caption = "Сервис автоматизации бурения", }, }); }); modelBuilder.Entity(entity => { entity.HasData(new List { new Deposit{Id = 1, Caption = "м/р 1", Latitude = 60.8705722222222, Longitude = 70.3811888888889 }, }); }); modelBuilder.Entity(entity => { entity.HasData(new List { new Cluster{Id = 1, Caption = "к39.1", IdDeposit = 1, Latitude = 60.8705722222222, Longitude = 70.3811888888889}, new Cluster{Id = 2, Caption = "к151", IdDeposit = 1, Latitude = 60.8205750000000, Longitude = 70.1343833333334}, new Cluster{Id = 3, Caption = "к611", IdDeposit = 1, Latitude = 60.8100666666667, Longitude = 69.7778388888889}, new Cluster{Id = 4, Caption = "к203", IdDeposit = 1, Latitude = 60.8928805555556, Longitude = 70.3272055555556}, new Cluster{Id = 5, Caption = "к221", IdDeposit = 1, Latitude = 60.6672055555556, Longitude = 69.6603861111111}, }); }); modelBuilder.Entity(entity => { entity.HasData(new List{ new Telemetry{ Id = 1, RemoteUid = "123", Info = new TelemetryInfo { Well = "1", Cluster = "1", Comment = "", Deposit = "1", Customer = "1", HmiVersion = "1", PlcVersion = "1", TimeZoneId = "1", DrillingStartDate = DateTime.Parse("2021-06-29T12:01:19.000000"), TimeZoneOffsetTotalHours = 5.0 }, } }); }); modelBuilder.Entity(entity => { entity.HasData(new List { new Well{Id = 1, IdCluster = 1, IdTelemetry = 1, Caption = "скв 16314", Latitude = 60.8705722222222, Longitude = 70.3811888888889}, new Well{Id = 2, IdCluster = 1, Caption = "скв 16311", Latitude = 60.8705722222222, Longitude = 70.3811888888889}, new Well{Id = 3, IdCluster = 2, Caption = "скв 16315", Latitude = 60.8205750000000, Longitude = 70.1343833333334}, new Well{Id = 4, IdCluster = 2, Caption = "скв 16318", Latitude = 60.8205750000000, Longitude = 70.1343833333334}, new Well{Id = 5, IdCluster = 3, Caption = "скв 16310", Latitude = 60.8100666666667, Longitude = 69.7778388888889}, new Well{Id = 6, IdCluster = 4, Caption = "скв 16316", Latitude = 60.8928805555556, Longitude = 70.3272055555556}, new Well{Id = 7, IdCluster = 5, Caption = "скв 16312", Latitude = 60.6672055555556, Longitude = 69.6603861111111}, new Well{Id = 8, IdCluster = 5, Caption = "скв 16313", Latitude = 60.6672055555556, Longitude = 69.6603861111111}, new Well{Id = 9, IdCluster = 5, Caption = "скв 42669", Latitude = 60.6672055555556, Longitude = 69.6603861111111}, }); }); modelBuilder.Entity(entity => { entity.HasData(new List { new RelationCompanyWell{ IdWell = 1, IdCompany = 1}, new RelationCompanyWell{ IdWell = 2, IdCompany = 1}, new RelationCompanyWell{ IdWell = 3, IdCompany = 1}, new RelationCompanyWell{ IdWell = 4, IdCompany = 1}, new RelationCompanyWell{ IdWell = 5, IdCompany = 1}, new RelationCompanyWell{ IdWell = 6, IdCompany = 1}, new RelationCompanyWell{ IdWell = 7, IdCompany = 1}, new RelationCompanyWell{ IdWell = 8, IdCompany = 1}, new RelationCompanyWell{ IdWell = 9, IdCompany = 1}, }); }); modelBuilder.Entity(entity => { entity.HasData(new List{ new TelemetryAnalysis { Id = 1, IdTelemetry = 1, IdOperation = 17, UnixDate = 1626870355, DurationSec = 10, OperationStartDepth = null, OperationEndDepth = 206, IsWellDepthIncreasing = false, IsWellDepthDecreasing = false, IsBitPositionIncreasing = false, IsBitPositionDecreasing = false, IsBitPositionLt20 = true, IsBlockPositionIncreasing = false, IsBlockPositionDecreasing = false, IsRotorSpeedLt3 = true, IsRotorSpeedGt3 = false, IsPressureLt20 = true, IsPressureGt20 = false, IsHookWeightNotChanges = true, IsHookWeightLt3 = true }, new TelemetryAnalysis { Id = 2, IdTelemetry = 1, IdOperation = 8, UnixDate = 1626870364, DurationSec = 6, OperationStartDepth = 206, OperationEndDepth = 206, IsWellDepthIncreasing = false, IsWellDepthDecreasing = false, IsBitPositionIncreasing = true, IsBitPositionDecreasing = false, IsBitPositionLt20 = true, IsBlockPositionIncreasing = true, IsBlockPositionDecreasing = false, IsRotorSpeedLt3 = true, IsRotorSpeedGt3 = false, IsPressureLt20 = true, IsPressureGt20 = false, IsHookWeightNotChanges = true, IsHookWeightLt3 = true }, new TelemetryAnalysis { Id = 3, IdTelemetry = 1, IdOperation = 10, UnixDate = 1626870370, DurationSec = 2, OperationStartDepth = 206, OperationEndDepth = 206, IsWellDepthIncreasing = false, IsWellDepthDecreasing = false, IsBitPositionIncreasing = false, IsBitPositionDecreasing = true, IsBitPositionLt20 = true, IsBlockPositionIncreasing = false, IsBlockPositionDecreasing = true, IsRotorSpeedLt3 = true, IsRotorSpeedGt3 = false, IsPressureLt20 = true, IsPressureGt20 = false, IsHookWeightNotChanges = true, IsHookWeightLt3 = true }, new TelemetryAnalysis { Id = 4, IdTelemetry = 1, IdOperation = 17, UnixDate = 1626870372, DurationSec = 7, OperationStartDepth = 206, OperationEndDepth = 206, IsWellDepthIncreasing = false, IsWellDepthDecreasing = false, IsBitPositionIncreasing = false, IsBitPositionDecreasing = false, IsBitPositionLt20 = true, IsBlockPositionIncreasing = false, IsBlockPositionDecreasing = false, IsRotorSpeedLt3 = true, IsRotorSpeedGt3 = false, IsPressureLt20 = true, IsPressureGt20 = false, IsHookWeightNotChanges = true, IsHookWeightLt3 = true }, new TelemetryAnalysis { Id = 5, IdTelemetry = 1, IdOperation = 8, UnixDate = 1626870379, DurationSec = 7, OperationStartDepth = 206, OperationEndDepth = 206, IsWellDepthIncreasing = false, IsWellDepthDecreasing = false, IsBitPositionIncreasing = true, IsBitPositionDecreasing = false, IsBitPositionLt20 = true, IsBlockPositionIncreasing = true, IsBlockPositionDecreasing = false, IsRotorSpeedLt3 = true, IsRotorSpeedGt3 = false, IsPressureLt20 = true, IsPressureGt20 = false, IsHookWeightNotChanges = true, IsHookWeightLt3 = true } }); }); } public IQueryable GetWellsForCompany(int idCompany) { return from well in Wells .Include(w => w.RelationCompaniesWells) .ThenInclude(r => r.Company) .Include(w => w.Cluster) .ThenInclude(c => c.Deposit) where well.RelationCompaniesWells.Any(c => c.IdCompany == idCompany) select well; } public IQueryable GetUsersByLogin(string login) => Users .Include(e => e.Role) .Include(e => e.Company) .Where(e => e.Login == login); public async Task<(DateTime From, DateTime To)> GetDatesRangeAsync(int idTelemetry, CancellationToken token = default) where TEntity : class, IIdTelemetryDate { var dbSet = Set(); var datesRange = await (from m in dbSet where m.IdTelemetry == idTelemetry group m by m.IdTelemetry into g select new { From = g.Min(d => d.Date), To = g.Max(d => d.Date) }).AsNoTracking().FirstOrDefaultAsync(token); if (datesRange is null) return (DateTime.MinValue, DateTime.MaxValue); return (datesRange.From, datesRange.To); } public async Task> GetDepthToIntervalAsync(int telemetryId, int intervalHoursTimestamp, int workStartTimestamp, double timezoneOffset, CancellationToken token) { //TODO: Сменить на LINQ группирование using var command = Database.GetDbConnection().CreateCommand(); command.CommandText = $@"SELECT Min(t.bit_depth) AS MinDepth, Max(t.bit_depth) AS MaxDepth, Min(t.Date) AS dateStart FROM t_data_saub_base AS t WHERE id_telemetry = {telemetryId} AND t.Id % 10 = 0 GROUP BY floor((extract(epoch from t.date) - {workStartTimestamp} + {timezoneOffset}) / {intervalHoursTimestamp});"; Database.OpenConnection(); using var reader = await command.ExecuteReaderAsync(token); IEnumerable<(double? MinDepth, double? MaxDepth, DateTime BeginPeriodDate)> GetResult(DbDataReader rd) { if (rd.HasRows) { while (reader.Read()) { yield return ( (double?)reader.GetValue(0), (double?)reader.GetValue(1), (DateTime)reader.GetValue(2) ); } } } return GetResult(reader); } public async Task CreatePartitionAsync(string propertyName, int id, CancellationToken token = default) where TEntity : class { var dbSet = Set(); var baseTableName = dbSet.EntityType.GetTableName(); var schema = dbSet.EntityType.GetSchema(); var tableObject = Microsoft.EntityFrameworkCore.Metadata.StoreObjectIdentifier.Table(baseTableName, schema); var tableName = baseTableName.Replace("_base", ""); var property = dbSet.EntityType.GetProperty(propertyName).GetColumnName(tableObject); var query = $"CREATE TABLE {tableName}_{id} (like {baseTableName} including all, constraint partitioning_check check ({property} = 1)) INHERITS ({baseTableName});"; return await Database.ExecuteSqlRawAsync(query, token).ConfigureAwait(false); } } }