100 lines
3.3 KiB
C#
100 lines
3.3 KiB
C#
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();
|
|
}
|
|
|
|
public void InsertBatch(
|
|
TestBatch batch,
|
|
IEnumerable<DissolutionSamplePoint> dissolutionSamples,
|
|
IEnumerable<HardnessSamplePoint>? hardnessSamples = null)
|
|
{
|
|
using var db = new AppDbContext(_connectionString);
|
|
db.TestBatches.Add(batch);
|
|
db.SaveChanges();
|
|
|
|
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);
|
|
|
|
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();
|
|
|
|
if (samples.Count > 0)
|
|
db.DissolutionSamplePoints.AddRange(samples);
|
|
|
|
if (hardnessDetails.Count == 0 && samples.Count == 0)
|
|
return;
|
|
|
|
db.SaveChanges();
|
|
batch.HardnessSamples = hardnessDetails;
|
|
batch.DissolutionSamples = samples;
|
|
}
|
|
|
|
public List<TestBatch> GetBatches(int? stationId = null, int limit = 100)
|
|
{
|
|
using var db = new AppDbContext(_connectionString);
|
|
var query = db.TestBatches
|
|
.Include(b => b.HardnessSamples)
|
|
.Include(b => b.DissolutionSamples)
|
|
.AsQueryable();
|
|
if (stationId.HasValue)
|
|
query = query.Where(b => b.StationId == stationId.Value);
|
|
query = query.OrderByDescending(b => b.TestTime).Take(limit);
|
|
return query.ToList();
|
|
}
|
|
|
|
public void DeleteBatch(int id)
|
|
{
|
|
using var db = new AppDbContext(_connectionString);
|
|
var batch = db.TestBatches.Find(id);
|
|
if (batch != null)
|
|
{
|
|
db.TestBatches.Remove(batch);
|
|
db.SaveChanges();
|
|
}
|
|
}
|
|
}
|
|
}
|