Files
DMS/ViewModels/DevicesViewModel.cs

92 lines
2.4 KiB
C#
Raw Normal View History

using System.Collections.ObjectModel;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PMSWPF.Data.Entities;
using PMSWPF.Data.Repositories;
using PMSWPF.Excptions;
using PMSWPF.Extensions;
using PMSWPF.Helper;
using PMSWPF.Models;
using PMSWPF.Services;
using PMSWPF.ViewModels.Dialogs;
using PMSWPF.Views.Dialogs;
2025-06-10 20:55:39 +08:00
namespace PMSWPF.ViewModels;
public partial class DevicesViewModel : ViewModelBase
2025-06-10 20:55:39 +08:00
{
private readonly IDeviceDialogService _deviceDialogService;
private readonly DevicesRepositories _devicesRepositories;
[ObservableProperty]
private ObservableCollection<Device> _devices;
public DevicesViewModel(IDeviceDialogService deviceDialogService,DevicesRepositories devicesRepositories)
{
_deviceDialogService = deviceDialogService;
_devicesRepositories = devicesRepositories;
_devices = new ObservableCollection<Device>();
}
public async Task OnLoadedAsync()
{
var ds = await _devicesRepositories.GetAll();
foreach (var dbDevice in ds)
{
var deviceExist= _devices.FirstOrDefault(d => d.Id == dbDevice.Id);
if (deviceExist == null)
{
Device device = new Device();
dbDevice.CopyTo(device);
_devices.Add(device);
}
}
}
[RelayCommand]
public async void AddDevice()
2025-06-10 22:13:06 +08:00
{
try
{
2025-06-12 18:56:25 +08:00
Device device= await _deviceDialogService.ShowAddDeviceDialog();
if (device != null)
{
DbDevice dbDevice = new DbDevice();
device.CopyTo<DbDevice>(dbDevice);
var rowCount= await _devicesRepositories.Add(dbDevice);
if (rowCount>0)
{
// MessageBox.Show("Device added successfully");
await OnLoadedAsync();
}
2025-06-12 18:56:25 +08:00
}
}
catch (DbExistException e)
{
Console.WriteLine(e);
MessageBox.Show(e.Message);
}
catch (Exception e)
{
Console.WriteLine(e);
MessageBox.Show(e.Message);
}
2025-06-10 22:13:06 +08:00
}
public override void OnLoaded()
{
OnLoadedAsync().Await((e) =>
{
_deviceDialogService.ShowMessageDialog("",e.Message);
}, () =>
{
});
}
2025-06-10 20:55:39 +08:00
}