86 lines
3.0 KiB
C#

using AmtScanner.Api.Data;
using AmtScanner.Api.Models;
using Microsoft.EntityFrameworkCore;
namespace AmtScanner.Api.Repositories;
public interface IHardwareInfoRepository
{
Task<HardwareInfo?> GetByDeviceIdAsync(long deviceId);
Task SaveAsync(HardwareInfo hardwareInfo);
Task<List<HardwareInfo>> GetByDeviceIdsAsync(List<long> deviceIds);
}
public class HardwareInfoRepository : IHardwareInfoRepository
{
private readonly AppDbContext _context;
public HardwareInfoRepository(AppDbContext context)
{
_context = context;
}
public async Task<HardwareInfo?> GetByDeviceIdAsync(long deviceId)
{
return await _context.HardwareInfos
.Include(h => h.MemoryModules)
.Include(h => h.StorageDevices)
.Include(h => h.Device)
.FirstOrDefaultAsync(h => h.DeviceId == deviceId);
}
public async Task SaveAsync(HardwareInfo hardwareInfo)
{
var existing = await GetByDeviceIdAsync(hardwareInfo.DeviceId);
if (existing != null)
{
// Remove old modules and devices
_context.MemoryModules.RemoveRange(existing.MemoryModules);
_context.StorageDevices.RemoveRange(existing.StorageDevices);
// Update existing
existing.LastUpdated = hardwareInfo.LastUpdated;
existing.SystemManufacturer = hardwareInfo.SystemManufacturer;
existing.SystemModel = hardwareInfo.SystemModel;
existing.SystemSerialNumber = hardwareInfo.SystemSerialNumber;
existing.ProcessorModel = hardwareInfo.ProcessorModel;
existing.ProcessorCores = hardwareInfo.ProcessorCores;
existing.ProcessorThreads = hardwareInfo.ProcessorThreads;
existing.ProcessorMaxClockSpeed = hardwareInfo.ProcessorMaxClockSpeed;
existing.ProcessorCurrentClockSpeed = hardwareInfo.ProcessorCurrentClockSpeed;
existing.TotalMemoryBytes = hardwareInfo.TotalMemoryBytes;
existing.UpdatedAt = DateTime.UtcNow;
// Add new modules and devices
foreach (var module in hardwareInfo.MemoryModules)
{
module.HardwareInfoId = existing.Id;
existing.MemoryModules.Add(module);
}
foreach (var device in hardwareInfo.StorageDevices)
{
device.HardwareInfoId = existing.Id;
existing.StorageDevices.Add(device);
}
}
else
{
_context.HardwareInfos.Add(hardwareInfo);
}
await _context.SaveChangesAsync();
}
public async Task<List<HardwareInfo>> GetByDeviceIdsAsync(List<long> deviceIds)
{
return await _context.HardwareInfos
.Include(h => h.MemoryModules)
.Include(h => h.StorageDevices)
.Include(h => h.Device)
.Where(h => deviceIds.Contains(h.DeviceId))
.ToListAsync();
}
}