Files
CSI-Z420-Tablet-Multi-Funct…/Helpers/DatabaseService.cs

89 lines
3.0 KiB
C#
Raw Normal View History

2026-05-05 15:31:24 +08:00
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using TabletTester2025.Data;
using TabletTester2025.Helpers;
using TabletTester2025.Models;
namespace TabletTester2025.Services
{
public class DatabaseService
{
private readonly string _connectionString;
public DatabaseService(string connectionString)
{
_connectionString = connectionString;
}
public void InsertBatch(TestBatch batch)
{
using var db = new AppDbContext(_connectionString);
db.TestBatches.Add(batch);
db.SaveChanges();
}
2026-05-19 20:33:16 +08:00
public void InsertBatch(
TestBatch batch,
IEnumerable<DissolutionSamplePoint> dissolutionSamples,
IEnumerable<HardnessSamplePoint>? hardnessSamples = null)
2026-05-18 14:06:04 +08:00
{
using var db = new AppDbContext(_connectionString);
db.TestBatches.Add(batch);
db.SaveChanges();
2026-05-19 20:33:16 +08:00
var hardnessDetails = (hardnessSamples ?? Enumerable.Empty<HardnessSamplePoint>())
.Where(s => double.IsFinite(s.Value) && s.Value > 0)
.OrderBy(s => s.SequenceNo)
.Select(s => new HardnessSamplePoint
{
TestBatchId = batch.Id,
SequenceNo = s.SequenceNo,
Value = s.Value,
DeviationFromAverage = s.DeviationFromAverage,
RecordedAt = s.RecordedAt
})
.ToList();
if (hardnessDetails.Count > 0)
db.HardnessSamplePoints.AddRange(hardnessDetails);
2026-05-18 14:06:04 +08:00
var samples = dissolutionSamples
.Where(s => s.Percent.HasValue)
.Select(s => new DissolutionSamplePoint
{
TestBatchId = batch.Id,
Channel = s.Channel,
ScheduledTimeMin = s.ScheduledTimeMin,
ActualTimeMin = s.ActualTimeMin,
Percent = s.Percent,
RecordedAt = s.RecordedAt
})
.ToList();
2026-05-19 20:33:16 +08:00
if (samples.Count > 0)
db.DissolutionSamplePoints.AddRange(samples);
if (hardnessDetails.Count == 0 && samples.Count == 0)
2026-05-18 14:06:04 +08:00
return;
db.SaveChanges();
2026-05-19 20:33:16 +08:00
batch.HardnessSamples = hardnessDetails;
2026-05-18 14:06:04 +08:00
batch.DissolutionSamples = samples;
}
2026-05-05 15:31:24 +08:00
public List<TestBatch> GetBatches(int? stationId = null, int limit = 100)
{
using var db = new AppDbContext(_connectionString);
2026-05-19 20:33:16 +08:00
var query = db.TestBatches
.Include(b => b.HardnessSamples)
.Include(b => b.DissolutionSamples)
.AsQueryable();
2026-05-05 15:31:24 +08:00
if (stationId.HasValue)
query = query.Where(b => b.StationId == stationId.Value);
query = query.OrderByDescending(b => b.TestTime).Take(limit);
return query.ToList();
}
}
2026-05-18 14:06:04 +08:00
}