添加数据库

This commit is contained in:
hsc 2025-12-03 13:30:31 +08:00
parent ace97f14a6
commit 7f2fa77dd2
38 changed files with 1732 additions and 170 deletions

View File

@ -6,9 +6,13 @@ using BOB.ViewModels.Dialogs;
using BOB.Views;
using BOB.Views.Dialogs;
using Castle.DynamicProxy;
using Model.SQLModel;
using ORM;
using Service.Implement;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows;
using static System.Runtime.InteropServices.JavaScript.JSType;
@ -30,15 +34,60 @@ namespace BOB
{
string deviceName = e.Args[0];
SystemConfig.Instance.Title = deviceName;
InitDataBase(deviceName);
//Debugger.Launch();
}
else
{
SystemConfig.Instance.Title = "设备2";//模拟打开的设备
InitDataBase("设备2");
}
base.OnStartup(e);
}
private void InitDataBase(string deviceName)
{
int tenantId = 0;
string dbFileName;
switch (deviceName)
{
case "设备1":
tenantId = 10001;
dbFileName = "设备1.db";
break;
case "设备2":
tenantId = 10002;
dbFileName = "设备2.db";
break;
case "设备3":
tenantId = 10003;
dbFileName = "设备3.db";
break;
case "水冷机和环境箱":
tenantId = 10004;
dbFileName = "水冷机和环境箱.db";
break;
default:
throw new Exception("未知设备");
}
// 设置租户 ID初始化雪花 ID WorkId/DatacenterId
DatabaseConfig.SetTenant(tenantId);
// 设置数据库路径
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string folder = Path.Combine(baseDir, "SQLDB");
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
string dbPath = Path.Combine(folder, dbFileName);
DatabaseConfig.SetDbConnection($"Data Source={dbPath}");
// 创建数据库文件并检查连接
DatabaseConfig.CreateDatabaseAndCheckConnection(createDatabase: true, checkConnection: true);
SqlSugarContext.DbContext.CodeFirst.InitTables(typeof(BackFeedData), typeof(EAELD9080Data), typeof(IT6724CData),typeof(PSB1100Data));
}
protected override void OnInitialized()
{
base.OnInitialized();
@ -64,15 +113,26 @@ namespace BOB
containerRegistry.RegisterDialog<SQ0030G1DView, SQ0030G1DViewModel>("SQ0030G1D");
containerRegistry.RegisterDialog<WS_68030_380TView, WS_68030_380TViewModel>("WS_68030_380T");
containerRegistry.RegisterDialog<ZXKSView, ZXKSViewModel>("ZXKS");
//注册全局变量
//注册全局单例变量
containerRegistry.RegisterSingleton<GlobalVariables>();
containerRegistry.RegisterSingleton<Devices>();
containerRegistry.RegisterSingleton<StepRunning>();
// 注册仓储
containerRegistry.RegisterScoped(typeof(SqlSugarRepository<>));
// 注册服务
containerRegistry.RegisterScoped(typeof(BackFeedService));
containerRegistry.RegisterScoped(typeof(EAEL9080Service));
containerRegistry.RegisterScoped(typeof(IT6724CService));
containerRegistry.RegisterScoped(typeof(LQ7500DService));
containerRegistry.RegisterScoped(typeof(PSB11000Service));
containerRegistry.RegisterScoped(typeof(SQ0030Service));
containerRegistry.RegisterScoped(typeof(WS680Service));
containerRegistry.RegisterScoped(typeof(ZXKXService));
}
protected override void OnExit(ExitEventArgs e)
{
//var devices = Container.Resolve<Devices>();
//devices.Dispose();
var devices = Container.Resolve<Devices>();
devices.Dispose();
base.OnExit(e);
}
}

View File

@ -1,6 +1,10 @@
using BOB.Singleton;
using Common.PubEvent;
using DeviceCommand.Device;
using Logger;
using Model.SQLModel;
using Service.Implement;
using Service.Interface;
using System;
using System.CodeDom;
using System.Collections.Generic;
@ -14,9 +18,11 @@ namespace BOB.Services
{
private Backfeed _Backfeed { get;set; }
private IEventAggregator _eventAggregator { get;set; }
private IBaseService<BackFeedData> _backFeedService { get;set; }
public BackfeedPollingRead(IContainerProvider containerProvider) : base(containerProvider)
{
_eventAggregator = containerProvider.Resolve<IEventAggregator>();
_backFeedService=containerProvider.Resolve<BackFeedService>();
var _devices = containerProvider.Resolve<Devices>();
DeviceName = "Backfeed";
_Backfeed = _devices.DeviceDic["Backfeed"]as Backfeed;
@ -33,14 +39,27 @@ namespace BOB.Services
//实时电流 =await _Backfeed!.查询实时电流(ct);
//实时电压 = await _Backfeed!.查询实时电压(ct);
//实时功率 = await _Backfeed!.查询实时功率(ct);
var datalist = new List<double>() { , , };
var dataDic = new Dictionary<string, double>
var reuslt= await _backFeedService.InsertAsync(new BackFeedData
{
RealTimeCurrent = ,
RealTimePower= ,
RealTimeVoltage= ,
CollectTime=DateTime.Now
});
if (reuslt.IsSuccess)
{
var dataDic = new Dictionary<string, double>
{
{ "实时电流", },
{ "实时电压", },
{ "实时功率", }
};
_eventAggregator.GetEvent<CurveDataEvent>().Publish(("Backfeed", dataDic));
_eventAggregator.GetEvent<CurveDataEvent>().Publish(("Backfeed", dataDic));
}
else
{
LoggerHelper.ErrorWithNotify(reuslt.Msg);
}
}
}
}

View File

@ -1,6 +1,10 @@
using BOB.Singleton;
using Common.PubEvent;
using DeviceCommand.Device;
using Logger;
using Model.SQLModel;
using Service.Implement;
using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
@ -13,10 +17,12 @@ namespace BOB.Services
{
private EAEL9080 _EAEL9080 { get; set; }
private IEventAggregator _eventAggregator { get; set; }
private IBaseService<EAELD9080Data> _eAEL9080Service { get; set; }
public EAEL9080PollingRead(IContainerProvider containerProvider) : base(containerProvider)
{
_eventAggregator = containerProvider.Resolve<IEventAggregator>();
var _devices = containerProvider.Resolve<Devices>();
_eAEL9080Service = containerProvider.Resolve<EAEL9080Service>();
DeviceName = "EAEL9080";
_EAEL9080 = _devices.DeviceDic["EAEL9080"] as EAEL9080;
}
@ -31,13 +37,28 @@ namespace BOB.Services
//实时电流 = await _EAEL9080!.查询电流(ct);
//实时电压 = await _EAEL9080!.查询电压(ct);
//实时功率 = await _EAEL9080!.查询功率(ct);
var dataDic = new Dictionary<string, double>
var reuslt = await _eAEL9080Service.InsertAsync(new EAELD9080Data
{
RealTimeCurrent = ,
RealTimePower = ,
RealTimeVoltage = ,
CollectTime = DateTime.Now
});
if (reuslt.IsSuccess)
{
var dataDic = new Dictionary<string, double>
{
{ "实时电流", },
{ "实时电压", },
{ "实时功率", }
};
_eventAggregator.GetEvent<CurveDataEvent>().Publish(("EAEL9080", dataDic));
_eventAggregator.GetEvent<CurveDataEvent>().Publish(("EAEL9080", dataDic));
}
else
{
LoggerHelper.ErrorWithNotify(reuslt.Msg);
}
}
}
}

View File

@ -1,6 +1,10 @@
using BOB.Singleton;
using Common.PubEvent;
using DeviceCommand.Device;
using Logger;
using Model.SQLModel;
using Service.Implement;
using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
@ -13,10 +17,12 @@ namespace BOB.Services
{
private IT6724C _IT6724C { get; set; }
private IEventAggregator _eventAggregator { get; set; }
private IBaseService<IT6724CData> _iT6724CService { get; set; }
public IT6724CPollingRead(IContainerProvider containerProvider) : base(containerProvider)
{
_eventAggregator = containerProvider.Resolve<IEventAggregator>();
var _devices = containerProvider.Resolve<Devices>();
_iT6724CService = containerProvider.Resolve<IT6724CService>();
DeviceName = "Backfeed";
_IT6724C = _devices.DeviceDic["IT6724C"] as IT6724C;
}
@ -31,13 +37,27 @@ namespace BOB.Services
//实时电流 = await _IT6724C!.查询实时电流(ct);
//实时电压 = await _IT6724C!.查询实时电压(ct);
//实时功率 = await _IT6724C!.查询实时功率(ct);
var dataDic = new Dictionary<string, double>
var reuslt = await _iT6724CService.InsertAsync(new IT6724CData
{
RealTimeCurrent = ,
RealTimePower = ,
RealTimeVoltage = ,
CollectTime = DateTime.Now
});
if (reuslt.IsSuccess)
{
var dataDic = new Dictionary<string, double>
{
{ "实时电流", },
{ "实时电压", },
{ "实时功率", }
};
_eventAggregator.GetEvent<CurveDataEvent>().Publish(("IT6724C", dataDic));
_eventAggregator.GetEvent<CurveDataEvent>().Publish(("IT6724C", dataDic));
}
else
{
LoggerHelper.ErrorWithNotify(reuslt.Msg);
}
}
}
}

View File

@ -1,6 +1,10 @@
using BOB.Singleton;
using Common.PubEvent;
using DeviceCommand.Device;
using Logger;
using Model.SQLModel;
using Service.Implement;
using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
@ -13,10 +17,12 @@ namespace BOB.Services
{
private PSB11000 _PSB11000 { get; set; }
private IEventAggregator _eventAggregator { get; set; }
private IBaseService<PSB1100Data> _pSB1100Service { get; set; }
public PSB11000PollingRead(IContainerProvider containerProvider) : base(containerProvider)
{
_eventAggregator = containerProvider.Resolve<IEventAggregator>();
var _devices = containerProvider.Resolve<Devices>();
_pSB1100Service = containerProvider.Resolve<PSB11000Service>();
DeviceName = "PSB11000";
_PSB11000 = _devices.DeviceDic["PSB11000"] as PSB11000;
}
@ -33,14 +39,27 @@ namespace BOB.Services
//实时电流 = await _PSB11000!.查询电流(ct);
//实时电压 = await _PSB11000!.查询电压(ct);
//实时功率 = await _PSB11000!.查询功率(ct);
var datalist = new List<double>() { , , };
var dataDic = new Dictionary<string, double>
var reuslt = await _pSB1100Service.InsertAsync(new PSB1100Data
{
RealTimeCurrent = ,
RealTimePower = ,
RealTimeVoltage = ,
CollectTime = DateTime.Now
});
if (reuslt.IsSuccess)
{
var dataDic = new Dictionary<string, double>
{
{ "实时电流", },
{ "实时电压", },
{ "实时功率", }
};
_eventAggregator.GetEvent<CurveDataEvent>().Publish(("PSB11000", dataDic));
_eventAggregator.GetEvent<CurveDataEvent>().Publish(("PSB11000", dataDic));
}
else
{
LoggerHelper.ErrorWithNotify(reuslt.Msg);
}
}
}
}

View File

@ -1,9 +1,18 @@
using BOB.Singleton;
using Common.PubEvent;
using Logger;
using Model.SQLModel;
using Prism.Commands;
using Prism.Mvvm;
using Service.Implement;
using Service.Interface;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace BOB.ViewModels
{
@ -11,38 +20,341 @@ namespace BOB.ViewModels
{
#region
private int _currentPage = 1;
public int CurrentPage
{
get => _currentPage;
set => SetProperty(ref _currentPage, value);
}
private RefAsync<int> _totalPages=new RefAsync<int>(0);
public RefAsync<int> TotalPages
{
get => _totalPages;
set => SetProperty(ref _totalPages, value);
}
private int _UITotalPages;
public int UITotalPages
{
get => _UITotalPages;
set => SetProperty(ref _UITotalPages, value);
}
private List<string> _dataTableList;
public List<string> DataTableList
{
get => _dataTableList;
set => SetProperty(ref _dataTableList, value);
}
private string _SelectTable;
public string SelectTable
{
get => _SelectTable;
set
{
if (SetProperty(ref _SelectTable, value))
{
}
}
}
private List<BackFeedData> _BackFeedDataList;
public List<BackFeedData> BackFeedDataList
{
get => _BackFeedDataList;
set => SetProperty(ref _BackFeedDataList, value);
}
private List<EAELD9080Data> _EAELD9080DataList;
public List<EAELD9080Data> EAELD9080DataList
{
get => _EAELD9080DataList;
set => SetProperty(ref _EAELD9080DataList, value);
}
private List<PSB1100Data> _PSB1100DataList;
public List<PSB1100Data> PSB1100DataList
{
get => _PSB1100DataList;
set => SetProperty(ref _PSB1100DataList, value);
}
private List<IT6724CData> _IT6724CDataList;
public List<IT6724CData> IT6724CDataList
{
get => _IT6724CDataList;
set => SetProperty(ref _IT6724CDataList, value);
}
private DateTime? _startDate;
public DateTime? StartDate
{
get => _startDate;
set => SetProperty(ref _startDate, value);
}
private DateTime? _endDate;
public DateTime? EndDate
{
get => _endDate;
set => SetProperty(ref _endDate, value);
}
private ObservableCollection<object> _currentDataSource;
public ObservableCollection<object> CurrentDataSource
{
get => _currentDataSource;
set => SetProperty(ref _currentDataSource, value);
}
#endregion
#region
public ICommand FirstPageCommand { get; private set; }
public ICommand PreviousPageCommand { get; private set; }
public ICommand NextPageCommand { get; private set; }
public ICommand LastPageCommand { get; private set; }
public ICommand LoadCommand { get; private set; }
public ICommand QueryCommand { get; private set; }
public ICommand RefreshCommand { get; private set; }
public ICommand SelectTableCommand { get; private set; }
#endregion
private IEventAggregator _eventAggregator;
private IDialogService _dialogService;
private Devices _devices { get; set; }
public DataViewModel(IEventAggregator eventAggregator, IDialogService dialogService, IContainerProvider containerProvider)
private IBaseService<BackFeedData> _backFeedService { get; set; }
private IBaseService<EAELD9080Data> _eAELD9080Service { get; set; }
private IBaseService<PSB1100Data> _pSB1100Service { get; set; }
private IBaseService<IT6724CData> _iT6724CService { get; set; }
public DataViewModel(IContainerProvider containerProvider)
{
_dialogService = dialogService;
_eventAggregator = eventAggregator;
_eventAggregator = containerProvider.Resolve<IEventAggregator>();
_dialogService = containerProvider.Resolve<IDialogService>();
_devices = containerProvider.Resolve<Devices>();
_backFeedService= containerProvider.Resolve<BackFeedService>();
_eAELD9080Service = containerProvider.Resolve<EAEL9080Service>();
_pSB1100Service = containerProvider.Resolve<PSB11000Service>();
_iT6724CService = containerProvider.Resolve<IT6724CService>();
FirstPageCommand = new AsyncDelegateCommand(GoToFirstPage);
PreviousPageCommand = new AsyncDelegateCommand(GoToPreviousPage);
NextPageCommand = new AsyncDelegateCommand(GoToNextPage);
LastPageCommand = new AsyncDelegateCommand(GoToLastPage);
LoadCommand = new AsyncDelegateCommand(Load);
QueryCommand = new AsyncDelegateCommand(Query);
RefreshCommand = new AsyncDelegateCommand(Refresh);
SelectTableCommand = new AsyncDelegateCommand(OnSelectTable);
DataTableList = new List<string> { "BackFeedData", "EAELD9080Data", "IT6724CData", "PSB1100Data"};
}
#region
public void OnNavigatedTo(NavigationContext navigationContext)
private async Task OnSelectTable()
{
switch (SelectTable)
{
case "BackFeedData":
CurrentDataSource = new ObservableCollection<object>(BackFeedDataList);
break;
case "EAELD9080Data":
CurrentDataSource = new ObservableCollection<object>(EAELD9080DataList);
break;
case "PSB1100Data":
CurrentDataSource = new ObservableCollection<object>(PSB1100DataList);
break;
case "IT6724CData":
CurrentDataSource = new ObservableCollection<object>(IT6724CDataList);
break;
default:
CurrentDataSource = new ObservableCollection<object>();
break;
}
GoToFirstPage();
}
private DateTime? QueryStartTime;
private DateTime? QueryEndTime;
private bool DataQuery=false;
private async Task Refresh()
{
DataQuery = false;
QueryStartTime = null;
QueryEndTime = null;
await GoToFirstPage();
}
private async Task Query()
{
if (!StartDate.HasValue || !EndDate.HasValue)
{
return;
}
DateTime endDateWithTime = EndDate.Value.AddDays(1);
if (StartDate.Value < endDateWithTime)
{
QueryStartTime = StartDate;
QueryEndTime = endDateWithTime;
DataQuery = true;
await GoToFirstPage();
}
else
{
return;
}
}
private async Task Load()
{
var backFeedResult = await _backFeedService.GetAllAsync();
if (backFeedResult.IsSuccess)
{
BackFeedDataList = backFeedResult.Data;
}
else
{
LoggerHelper.ErrorWithNotify("加载 BackFeed 数据失败");
}
var eaELD9080Result = await _eAELD9080Service.GetAllAsync();
if (eaELD9080Result.IsSuccess)
{
EAELD9080DataList = eaELD9080Result.Data;
}
else
{
LoggerHelper.ErrorWithNotify("加载 EAELD9080 数据失败");
}
var pSB1100Result = await _pSB1100Service.GetAllAsync();
if (pSB1100Result.IsSuccess)
{
PSB1100DataList = pSB1100Result.Data;
}
else
{
LoggerHelper.ErrorWithNotify("加载 PSB1100 数据失败");
}
var it6724CResult = await _iT6724CService.GetAllAsync();
if (it6724CResult.IsSuccess)
{
IT6724CDataList = it6724CResult.Data;
}
else
{
LoggerHelper.ErrorWithNotify("加载 IT6724C 数据失败");
}
}
private async Task GoToFirstPage()
{
CurrentPage = 1;
await LoadPageData(CurrentPage);
}
private async Task GoToPreviousPage()
{
if (CurrentPage > 1)
{
CurrentPage--;
await LoadPageData(CurrentPage);
}
}
private async Task GoToNextPage()
{
if (CurrentPage < TotalPages)
{
CurrentPage++;
await LoadPageData(CurrentPage);
}
}
private async Task GoToLastPage()
{
CurrentPage = TotalPages;
await LoadPageData(CurrentPage);
}
private int PageSize=20;
private async Task LoadPageData(int currentPage)
{
switch (SelectTable)
{
case "BackFeedData":
if (DataQuery) // 如果启用日期查询
{
var result = await _backFeedService.GetPagedAsync(currentPage, PageSize, TotalPages, QueryStartTime, QueryEndTime);
if (result.IsSuccess)
CurrentDataSource = new ObservableCollection<object>(result.Data);
}
else
{
var result = await _backFeedService.GetPagedAsync(currentPage, PageSize, TotalPages);
if (result.IsSuccess)
CurrentDataSource = new ObservableCollection<object>(result.Data);
}
break;
case "EAELD9080Data":
if (DataQuery)
{
var result = await _eAELD9080Service.GetPagedAsync(currentPage, PageSize, TotalPages, QueryStartTime, QueryEndTime);
if (result.IsSuccess)
CurrentDataSource = new ObservableCollection<object>(result.Data);
}
else
{
var result = await _eAELD9080Service.GetPagedAsync(currentPage, PageSize, TotalPages);
if (result.IsSuccess)
CurrentDataSource = new ObservableCollection<object>(result.Data);
}
break;
case "PSB1100Data":
if (DataQuery)
{
var result = await _pSB1100Service.GetPagedAsync(currentPage, PageSize, TotalPages, QueryStartTime, QueryEndTime);
if (result.IsSuccess)
CurrentDataSource = new ObservableCollection<object>(result.Data);
}
else
{
var result = await _pSB1100Service.GetPagedAsync(currentPage, PageSize, TotalPages);
if (result.IsSuccess)
CurrentDataSource = new ObservableCollection<object>(result.Data);
}
break;
case "IT6724CData":
if (DataQuery)
{
var result = await _iT6724CService.GetPagedAsync(currentPage, PageSize, TotalPages, QueryStartTime, QueryEndTime);
if (result.IsSuccess)
CurrentDataSource = new ObservableCollection<object>(result.Data);
}
else
{
var result = await _iT6724CService.GetPagedAsync(currentPage, PageSize, TotalPages);
if (result.IsSuccess)
CurrentDataSource = new ObservableCollection<object>(result.Data);
}
break;
default:
CurrentDataSource = new ObservableCollection<object>();
break;
}
UITotalPages = TotalPages.Value;
}
#region
public void OnNavigatedTo(NavigationContext navigationContext) { }
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
public void OnNavigatedFrom(NavigationContext navigationContext)
{
public void OnNavigatedFrom(NavigationContext navigationContext) { }
}
#endregion
}
}

View File

@ -32,59 +32,8 @@ namespace BOB.ViewModels
var brush = (Brush)new BrushConverter().ConvertFromString(log.color);
Logs.Add(new LogItem(log.message, brush, log.depth));
});
//ShowDeviesInfo();
}
//private void ShowDeviesInfo()
//{
// foreach (var kv in devices.DeviceDic)
// {
// string name = kv.Key;
// object dev = kv.Value;
// if (dev == null)
// {
// LoggerHelper.InfoWithNotify($"{name} 实例为空", 0);
// continue;
// }
// string typeName = dev.GetType().Name;
// string status = GetDeviceConnectionStatus(dev);
// LoggerHelper.InfoWithNotify(
// $"设备:{name} | 类型:{typeName} | {status}", 0);
// }
//}
//private string GetDeviceConnectionStatus(object device)
//{
// // 串口设备
// var serialField = device.GetType().GetProperty("_SerialPort",
// BindingFlags.Public | BindingFlags.Instance);
// if (serialField != null)
// {
// var serial = serialField.GetValue(device) as System.IO.Ports.SerialPort;
// if (serial == null)
// return "串口未初始化";
// return serial.IsOpen ? "串口已连接" : "串口未连接";
// }
// // TCP 设备
// var tcpProperty = device.GetType().GetProperty(
// "TcpClient",
// BindingFlags.Public | BindingFlags.Instance
// );
// if (tcpProperty != null)
// {
// var client = tcpProperty.GetValue(device) as System.Net.Sockets.TcpClient;
// if (client == null)
// return "TCP 未初始化";
// return client.Connected ? "TCP 已连接" : "TCP 未连接";
// }
// return "无法识别设备类型";
//}
private void ClearLog()

View File

@ -6,55 +6,124 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vs="clr-namespace:BOB.Views"
xmlns:oxy="http://oxyplot.org/wpf"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
d:DesignHeight="1080"
d:DesignWidth="1920">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding LoadCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DataGrid ItemsSource="{Binding CurrentDataSource}"
AutoGenerateColumns="True"
Margin="20,20,0,0" />
<GroupBox Header="数据处理"
Grid.Row="1"
Margin="5"
Padding="0">
<StackPanel Orientation="Horizontal"
Margin="5">
<!-- 数据保存按钮 -->
<Button Content="保存数据"
Command="{Binding SaveCommand}"
Margin="10,0,10,0" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<!-- 查询输入框 -->
<TextBox x:Name="QueryTextBox"
Width="200"
Margin="0,0,10,0" />
<TextBlock VerticalAlignment="Center"
Margin="10,0,10,0"
Text="起始日期:" />
<DatePicker x:Name="StartDatePicker"
Width="120"
Margin="0,0,10,0"
SelectedDate="{Binding StartDate, Mode=TwoWay}" />
<TextBlock VerticalAlignment="Center"
Margin="10,0,10,0"
Text="结束日期:" />
<DatePicker x:Name="EndDatePicker"
Width="120"
Margin="0,0,10,0"
SelectedDate="{Binding EndDate, Mode=TwoWay}" />
<!-- 查询按钮 -->
<Button Content="查询"
Command="{Binding QueryCommand}"
CommandParameter="{Binding Text, ElementName=QueryTextBox}"
Margin="10,0,0,0" />
</StackPanel>
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Left"
Margin="5">
<ComboBox ItemsSource="{Binding DataTableList}"
SelectedItem="{Binding SelectTable, Mode=TwoWay}"
MinWidth="150"
materialDesign:HintAssist.Hint=""
Margin="15,0,15,0" />
<Button Content="选择数据表"
Command="{Binding SelectTableCommand}"
Margin="15,0,15,0" />
<!-- 查询输入框 -->
<!--<TextBox x:Name="QueryTextBox"
Width="200"
Margin="0,0,10,0" />
--><!-- 查询按钮 --><!--
<Button Content="查询"
Command="{Binding QueryCommand}"
CommandParameter="{Binding Text, ElementName=QueryTextBox}"
Margin="10,0,20,0" />-->
</StackPanel>
<!-- 右侧内容: 日期选择器 -->
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Margin="5">
<TextBlock VerticalAlignment="Center"
Margin="15,0,15,0"
Text="起始日期:" />
<DatePicker materialDesign:HintAssist.Hint="起始日期"
materialDesign:TextFieldAssist.HasClearButton="True"
Style="{StaticResource MaterialDesignFloatingHintDatePicker}"
Width="120"
Margin="0,0,10,0"
SelectedDate="{Binding StartDate, Mode=TwoWay}" />
<TextBlock VerticalAlignment="Center"
materialDesign:HintAssist.Hint=""
Margin="15,0,15,0"
Text="结束日期:" />
<DatePicker materialDesign:HintAssist.Hint="结束日期"
materialDesign:TextFieldAssist.HasClearButton="True"
Style="{StaticResource MaterialDesignFloatingHintDatePicker}"
Width="120"
Margin="0,0,10,0"
SelectedDate="{Binding EndDate, Mode=TwoWay}" />
<!-- 查询按钮 -->
<Button Content="查询"
Command="{Binding QueryCommand}"
Margin="10,0,0,0" />
<Button Content="刷新数据"
Command="{Binding RefreshCommand}"
Margin="15,0,15,0" />
</StackPanel>
<!-- 分页控件 -->
<StackPanel Grid.Row="1"
Grid.Column="1"
Orientation="Horizontal"
HorizontalAlignment="Center"
Margin="5">
<Button Content="第一页"
Command="{Binding FirstPageCommand}"
Margin="10,0,10,0" />
<Button Content="上一页"
Command="{Binding PreviousPageCommand}"
Margin="10,0,10,0" />
<TextBlock VerticalAlignment="Center"
Margin="10 10 0 10"
Text="{Binding CurrentPage}"
materialDesign:HintAssist.Hint="" />
<TextBlock Text="/"
Margin="0 10"
materialDesign:HintAssist.Hint="" />
<TextBlock Text="{Binding UITotalPages}"
materialDesign:HintAssist.Hint=""
Margin="0 10" />
<Button Content="下一页"
Command="{Binding NextPageCommand}"
Margin="10,0,10,0" />
<Button Content="最后一页"
Command="{Binding LastPageCommand}"
Margin="10,0,15,0" />
</StackPanel>
</Grid>
</GroupBox>
</Grid>
</UserControl>

View File

@ -16,8 +16,9 @@
TargetType="Window" />
</prism:Dialog.WindowStyle>
<GroupBox Header="IO板卡手动设置"
Padding="0,0,0,0">
<Grid MouseLeftButtonDown="MouseLeftButtonDown">
Padding="0,0,0,0"
MouseLeftButtonDown="MouseLeftButtonDown">
<Grid >
<TreeView Margin="10">
<TreeViewItem Header="连接状态设置">
<StackPanel Orientation="Horizontal">

View File

@ -17,8 +17,9 @@
TargetType="Window" />
</prism:Dialog.WindowStyle>
<GroupBox Header="AC源手动设置"
Padding="0,0,0,0">
<Grid MouseLeftButtonDown="MouseLeftButtonDown">
Padding="0,0,0,0"
MouseLeftButtonDown="MouseLeftButtonDown">
<Grid >
<TreeView Margin="10">
<TreeViewItem Header="连接状态设置">
<StackPanel Orientation="Horizontal">

View File

@ -17,8 +17,9 @@
TargetType="Window" />
</prism:Dialog.WindowStyle>
<GroupBox Header="AC载手动设置"
Padding="0,0,0,0">
<Grid MouseLeftButtonDown="MouseLeftButtonDown">
Padding="0,0,0,0"
MouseLeftButtonDown="MouseLeftButtonDown">
<Grid >
<TreeView Margin="10">
<TreeViewItem Header="连接状态设置">
<StackPanel Orientation="Horizontal">

View File

@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SqlSugarCore" Version="5.1.4.210" />
<PackageReference Include="System.IO.Ports" Version="10.0.0" />
</ItemGroup>

180
Model/Result.cs Normal file
View File

@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public class Result
{
public Result()
{
}
private int _code;
private readonly string _msg;
/// <summary>
/// 结果是否成功
/// </summary>
public bool IsSuccess => _code == 0;
/// <summary>
/// 结果代码
/// </summary>
public int Code { set => _code = value; get => _code; }
/// <summary>
/// 结果消息
/// </summary>
public string Msg => _msg;
/// <summary>
/// 构造方法
/// </summary>
/// <param name="code"></param>
/// <param name="msg"></param>
/// <param name="exception"></param>
protected Result(int code, string msg, Exception? exception = null)
{
if (exception != null)
{
var listMoreMsg = new List<string>();
if (exception is ResultException resultException)
{
listMoreMsg.AddRange(resultException.MessageList);
}
//else if (exception is DeviceControlException deviceControlException)
//{
// listMoreMsg.Add(deviceControlException.ErrorInfo);
//}
else
{
listMoreMsg.Add(exception.Message);
}
var strMoreMsg = string.Join("、", listMoreMsg.Where(it => !string.IsNullOrWhiteSpace(it)));
if (!string.IsNullOrWhiteSpace(strMoreMsg))
{
msg += $"{strMoreMsg}";
}
}
_code = code;
_msg = msg;
}
/// <summary>
/// 返回成功结果
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static Result Success()
{
return new Result(0, "");
}
/// <summary>
/// 返回错误结果
/// </summary>
/// <param name="msg"></param>
/// <param name="exception"></param>
/// <returns></returns>
public static Result Error(string msg, Exception? exception = null)
{
return new Result(-1, msg, exception);
}
}
public class Result<T> : Result
{
public Result()
{
}
private T? _data;
/// <summary>
/// 结果数据
/// </summary>
public T? Data { set => _data = value; get => _data; }
/// <summary>
/// 构造方法
/// </summary>
/// <param name="code"></param>
/// <param name="msg"></param>
/// <param name="data"></param>
/// <param name="exception"></param>
private Result(int code, string msg, T? data, Exception? exception = null) : base(code, msg, exception)
{
_data = data;
}
/// <summary>
/// 返回成功数据
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static Result<T> Success(T data)
{
return new Result<T>(0, "", data);
}
/// <summary>
/// 返回失败信息
/// </summary>
/// <param name="msg"></param>
/// <param name="exception"></param>
/// <returns></returns>
public new static Result<T> Error(string msg, Exception? exception = null)
{
return new Result<T>(-1, msg, default, exception);
}
/// <summary>
/// 返回失败信息和数据
/// </summary>
/// <param name="msg"></param>
/// <param name="data"></param>
/// <param name="exception"></param>
/// <returns></returns>
public static Result<T> Error(string msg, T data, Exception? exception = null)
{
return new Result<T>(-1, msg, data, exception);
}
}
public class ResultException : Exception
{
private List<string>? _messageList;
public List<string> MessageList
{
get
{
List<string> messages = new();
if (_messageList != null)
{
messages.AddRange(_messageList.Where(it => !string.IsNullOrWhiteSpace(it)));
}
return messages;
}
}
public override string Message => string.Join(", ", MessageList);
public ResultException() : base(null)
{
}
public void AddAdditionMessage(string message)
{
_messageList ??= new();
_messageList.Add(message);
}
}
}

View File

@ -0,0 +1,16 @@
using SqlSugar;
using System;
namespace Model.SQLModel
{
public class BackFeedData : BaseEntity
{
public double RealTimeCurrent { get; set; }
public double RealTimeVoltage { get; set; }
public double RealTimePower { get; set; }
}
}

View File

@ -0,0 +1,27 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.SQLModel
{
public class BaseEntity
{
/// <summary>
/// 主键Id
/// </summary>
[SugarColumn(ColumnName = "id", ColumnDescription = "主键Id", IsPrimaryKey = true, CreateTableFieldSort = 0)]
public virtual long Id { get; set; }
/// <summary>
/// 删除状态
/// </summary>
[SugarColumn(ColumnName = "IsDel", ColumnDescription = "删除状态0、未删除1、已删除", ColumnDataType = "tinyint", DefaultValue = "0", CreateTableFieldSort = 106)]
public virtual byte IsDel { get; set; }
[SugarColumn(ColumnName = "CollectTime")]
public DateTime CollectTime { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.SQLModel
{
public class EAELD9080Data:BaseEntity
{
public double RealTimeCurrent { get; set; }
public double RealTimeVoltage { get; set; }
public double RealTimePower { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.SQLModel
{
public class IT6724CData : BaseEntity
{
public double RealTimeCurrent { get; set; }
public double RealTimeVoltage { get; set; }
public double RealTimePower { get; set; }
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.SQLModel
{
public class LQ7500Data : BaseEntity
{
}
}

View File

@ -0,0 +1,16 @@
using SqlSugar;
using System;
namespace Model.SQLModel
{
public class PSB1100Data : BaseEntity
{
public double RealTimeCurrent { get; set; }
public double RealTimeVoltage { get; set; }
public double RealTimePower { get; set; }
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.SQLModel
{
public class SQ0030Data : BaseEntity
{
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.SQLModel
{
public class WS680Data:BaseEntity
{
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.SQLModel
{
public class ZXKSData : BaseEntity
{
}
}

View File

@ -1,97 +1,101 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ORM
{
public static class DatabaseConfig
public class DatabaseConfig
{
/// <summary>
/// 当前数据库类型
/// 数据库连接类型
/// </summary>
public static DbType DbConnectionType { get; private set; }
public static DbType DbConnectionType => DbType.Sqlite;
/// <summary>
/// 数据库连接字符串
/// SQLite 数据库文件路径
/// </summary>
public static string DbConnectionString { get; private set; }
/// <summary>
/// 默认 SQLite 文件路径(仅记录,不自动启用)
/// </summary>
public static string DefaultDbFilePath { get; private set; }
/// <summary>
/// 租户 Id
/// 数据租户Id
/// </summary>
public static int TenantId { get; private set; }
/// <summary>
/// 雪花算法DatacenterId值范围0至31
/// </summary>
public static int SnowFlakeDatacenterId { get; private set; }
/// <summary>
/// 雪花算法WorkID值范围0至31
/// </summary>
public static int SnowFlakeWorkId { get; private set; }
static DatabaseConfig()
{
InitDefaultDbPath(); // 只生成路径,不指定 DB 类型/连接
}
/// <summary>
/// 生成默认 DB 路径 EXE目录/SQLDB/Data.db
/// </summary>
private static void InitDefaultDbPath()
{
// 获取程序运行目录
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
// 确保 SQLDB 文件夹存在
string folder = Path.Combine(baseDir, "SQLDB");
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
DefaultDbFilePath = Path.Combine(folder, "Data.db");
// 拼接数据库文件路径
string dbPath = Path.Combine(folder, "SQL.db");
// 设置连接字符串
DbConnectionString = $"Data Source={dbPath};Version=3;";
}
/// <summary>
/// 手动设置数据库连接
/// 设置数据库连接字符串(可手动覆盖)
/// </summary>
public static void SetConnection(string conn, DbType dbType)
public static void SetDbConnection(string strConnection)
{
if (string.IsNullOrWhiteSpace(conn))
throw new Exception("数据库连接字符串为空");
DbConnectionString = conn;
DbConnectionType = dbType;
}
/// <summary>
/// 如果未 SetConnection默认使用 SQLite + 默认路径
/// </summary>
public static void EnsureConnection()
{
if (string.IsNullOrEmpty(DbConnectionString))
if (string.IsNullOrEmpty(strConnection))
{
DbConnectionString = $"Data Source={DefaultDbFilePath};";
DbConnectionType = DbType.Sqlite;
throw new Exception("数据库连接字符串为空");
}
DbConnectionString = strConnection;
}
/// <summary>
/// 设置租户并计算雪花算法节点
/// 设置数据租户Id
/// </summary>
public static void SetTenant(int tenantId)
public static void SetTenant(int nTenantId)
{
if (tenantId <= 10000)
if (nTenantId <= 10000)
{
throw new Exception("数据租户Id值需大于10000");
}
TenantId = nTenantId;
SetSnowFlake((nTenantId - 10000) % 1024);
}
TenantId = tenantId;
int snowId = (tenantId - 10000) % 1024;
if (snowId is < 0 or > 1023)
/// <summary>
/// 将指定数字转换为雪花算法DatacenterId和WorkID
/// </summary>
private static void SetSnowFlake(int nSnowFlakeId)
{
if (nSnowFlakeId > 1023 || nSnowFlakeId < 0)
{
throw new Exception("雪花算法机器码值范围0至1023");
SnowFlakeDatacenterId = snowId >> 5;
SnowFlakeWorkId = snowId & 31;
}
SnowFlakeDatacenterId = nSnowFlakeId >> 5;
SnowFlakeWorkId = nSnowFlakeId & 31;
}
public static void CreateDatabaseAndCheckConnection(bool createDatabase = false, bool checkConnection = false)
{
//数据库不存在则创建数据库
if (createDatabase)
{
SqlSugarContext.DbContext.DbMaintenance.CreateDatabase();
}
// 检查数据库连接
if (checkConnection && !SqlSugarContext.DbContext.Ado.IsValidConnection())
{
throw new Exception("连接数据库失败");
}
}
}
}

85
ORM/SqlSugarContext.cs Normal file
View File

@ -0,0 +1,85 @@
using Logger;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ORM
{
public class SqlSugarContext
{
/// <summary>
/// SqlSugarScope单例模式
/// </summary>
public static readonly SqlSugarScope DbContext = new SqlSugarScope(
new ConnectionConfig()
{
DbType = DatabaseConfig.DbConnectionType,
ConnectionString = DatabaseConfig.DbConnectionString, // 连接符字串
//ConfigId = "Db1",//管理多个数据库
IsAutoCloseConnection = true, // 自动关闭连接
InitKeyType = InitKeyType.Attribute // 通过实体类上的特性初始化
},
db =>
{
// 执行超时时间,单位秒
db.Ado.CommandTimeOut = 30;
// 每次SQL执行前事件
db.Aop.OnLogExecuting = (sql, pars) =>
{
#if DEBUG
// 确保 SQL 只通过 sqlLogger 记录
LoggerHelper.sqlLogger.Info("Executing SQL: {0} with parameters: {1}", sql, pars); // 使用 NLog 记录 SQL
#endif
};
// SQL执行完
db.Aop.OnLogExecuted = (sql, pars) =>
{
// 执行时间超过1秒记录慢日志
if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
{
LoggerHelper.sqlLogger.Warn("SQL Slow Execution. Time: {0}, File: {1}, Line: {2}, Method: {3}, SQL: {4}",
db.Ado.SqlExecutionTime.ToString(), // SQL 执行时间
db.Ado.SqlStackTrace.FirstFileName, // 代码 CS 文件名
db.Ado.SqlStackTrace.FirstLine, // 代码行数
db.Ado.SqlStackTrace.FirstMethodName, // 代码方法名
sql); // 使用 NLog 记录慢 SQL 日志
}
};
// SQL 报错
db.Aop.OnError = (exp) =>
{
// 确保 SQL 错误日志仅通过 sqlLogger 记录
LoggerHelper.sqlLogger.Error(exp, "SQL Error: {0}", exp.Sql); // 使用 NLog 记录 SQL 错误日志
};
// 数据过滤器:例如在新增数据时生成雪花 Id
db.Aop.DataExecuting = (oldValue, entityInfo) =>
{
// 新增操作
if (entityInfo.OperationType == DataFilterType.InsertByObject)
{
// 主键(long)赋值雪花 Id
if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
{
var id = ((dynamic)entityInfo.EntityValue).Id;
if (id == null || id == 0)
{
SnowFlakeSingle.WorkId = DatabaseConfig.SnowFlakeWorkId;
SnowFlakeSingle.DatacenterId = DatabaseConfig.SnowFlakeDatacenterId;
entityInfo.SetValue(SnowFlakeSingle.Instance.NextId());
}
}
}
};
}
);
}
}

396
ORM/SqlSugarRepository.cs Normal file
View File

@ -0,0 +1,396 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ORM
{
public partial class SqlSugarRepository<TEntity> : SimpleClient<TEntity> where TEntity : class, new()
{
/// <summary>
/// 实体集合
/// </summary>
public ISugarQueryable<TEntity> Entities => Context.Queryable<TEntity>();
/// <summary>
/// 构造函数
/// </summary>
public SqlSugarRepository(ISqlSugarClient context = null) : base(context)
{
// 绑定数据库操作对象
Context = SqlSugarContext.DbContext;
// 备忘GetConnectionScopeWithAttr会导致不能触发Aop.OnLogExecuting、Aop.OnLogExecuted等事件
// 详见https://www.donet5.com/Home/Doc?typeId=2405之2.1、方法说明)
// 详见https://www.donet5.com/Home/Doc?typeId=2246之2.2、根据特性获取之4、多租户设置AOP
// base.Context = SqlSugarContext.DbContext.GetConnectionScopeWithAttr<TEntity>();
// 根据特性获取,适合一个实体和库是一对一的情况
}
#region
/// <summary>
/// 检查是否存在
/// </summary>
/// <param name="whereExpression"></param>
/// <returns></returns>
public bool IsExists(Expression<Func<TEntity, bool>> whereExpression)
{
return Entities.Any(whereExpression);
}
/// <summary>
/// 检查是否存在
/// </summary>
/// <param name="whereExpression"></param>
/// <returns></returns>
public async Task<bool> IsExistsAsync(Expression<Func<TEntity, bool>> whereExpression)
{
return await Entities.AnyAsync(whereExpression);
}
/// <summary>
/// 通过主键获取实体
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public TEntity Single(dynamic Id)
{
return Entities.InSingle(Id);
}
/// <summary>
/// 获取一个实体
/// </summary>
/// <param name="whereExpression"></param>
/// <returns></returns>
public TEntity Single(Expression<Func<TEntity, bool>> whereExpression)
{
return Entities.Single(whereExpression);
}
/// <summary>
/// 获取一个实体
/// </summary>
/// <param name="whereExpression"></param>
/// <returns></returns>
public Task<TEntity> SingleAsync(Expression<Func<TEntity, bool>> whereExpression)
{
return Entities.SingleAsync(whereExpression);
}
/// <summary>
/// 获取一个实体
/// </summary>
/// <param name="whereExpression"></param>
/// <returns></returns>
public TEntity FirstOrDefault(Expression<Func<TEntity, bool>> whereExpression)
{
return Entities.First(whereExpression);
}
/// <summary>
/// 获取一个实体
/// </summary>
/// <param name="whereExpression"></param>
/// <returns></returns>
public async Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> whereExpression)
{
return await Entities.FirstAsync(whereExpression);
}
/// <summary>
/// 获取列表
/// </summary>
/// <returns></returns>
public List<TEntity> ToList()
{
return Entities.ToList();
}
/// <summary>
/// 获取列表
/// </summary>
/// <returns></returns>
public Task<List<TEntity>> ToListAsync()
{
return Entities.ToListAsync();
}
/// <summary>
/// 获取列表
/// </summary>
/// <param name="whereExpression"></param>
/// <returns></returns>
public List<TEntity> ToList(Expression<Func<TEntity, bool>> whereExpression)
{
return Entities.Where(whereExpression).ToList();
}
/// <summary>
/// 获取列表
/// </summary>
/// <param name="whereExpression"></param>
/// <returns></returns>
public Task<List<TEntity>> ToListAsync(Expression<Func<TEntity, bool>> whereExpression)
{
return Entities.Where(whereExpression).ToListAsync();
}
/// <summary>
/// 获取列表
/// </summary>
/// <param name="whereExpression"></param>
/// <param name="orderByExpression"></param>
/// <param name="orderByType"></param>
/// <returns></returns>
public List<TEntity> ToList(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
{
return Entities.OrderByIF(orderByExpression != null, orderByExpression, orderByType).Where(whereExpression).ToList();
}
/// <summary>
/// 获取列表
/// </summary>
/// <param name="whereExpression"></param>
/// <param name="orderByExpression"></param>
/// <param name="orderByType"></param>
/// <returns></returns>
public Task<List<TEntity>> ToListAsync(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
{
return Entities.OrderByIF(orderByExpression != null, orderByExpression, orderByType).Where(whereExpression).ToListAsync();
}
#endregion
#region
/// <summary>
/// 新增多条记录
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public int Insert(TEntity[] entities)
{
return Context.Insertable(entities).ExecuteCommand();
}
/// <summary>
/// 新增多条记录
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public Task<int> InsertAsync(TEntity[] entities)
{
return Context.Insertable(entities).ExecuteCommandAsync();
}
/// <summary>
/// 新增多条记录
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public int Insert(IEnumerable<TEntity> entities)
{
return Context.Insertable(entities.ToArray()).ExecuteCommand();
}
/// <summary>
/// 新增多条记录
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public Task<int> InsertAsync(IEnumerable<TEntity> entities)
{
if (entities != null && entities.Any())
{
return Context.Insertable(entities.ToArray()).ExecuteCommandAsync();
}
return Task.FromResult(0);
}
#endregion
#region
/// <summary>
/// 更新单条记录指定列
/// </summary>
/// <param name="entity"></param>
/// <param name="updateColumn"></param>
/// <returns></returns>
public int Update(TEntity entity, object updateColumn)
{
return Context.Updateable(entity).UpdateColumns(MergeUpdateColumns(updateColumn)).ExecuteCommand();
}
/// <summary>
/// 更新单条记录指定列
/// </summary>
/// <param name="entity"></param>
/// <param name="updateColumn"></param>
/// <returns></returns>
public Task<int> UpdateAsync(TEntity entity, object updateColumn)
{
return Context.Updateable(entity).UpdateColumns(MergeUpdateColumns(updateColumn)).ExecuteCommandAsync();
}
/// <summary>
/// 更新单条记录指定列
/// </summary>
/// <param name="entity"></param>
/// <param name="updateColumn"></param>
/// <param name="whereExpression"></param>
/// <returns></returns>
public int Update(TEntity entity, object updateColumn, Expression<Func<TEntity, bool>> whereExpression)
{
return Context.Updateable(entity).UpdateColumns(MergeUpdateColumns(updateColumn)).Where(whereExpression).ExecuteCommand();
}
/// <summary>
/// 更新单条记录指定列
/// </summary>
/// <param name="entity"></param>
/// <param name="updateColumn"></param>
/// <param name="whereExpression"></param>
/// <returns></returns>
public Task<int> UpdateAsync(TEntity entity, object updateColumn, Expression<Func<TEntity, bool>> whereExpression)
{
return Context.Updateable(entity).UpdateColumns(MergeUpdateColumns(updateColumn)).Where(whereExpression).ExecuteCommandAsync();
}
/// <summary>
/// 更新多条记录
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public int Update(TEntity[] entities)
{
return Context.Updateable(entities).ExecuteCommand();
}
/// <summary>
/// 更新多条记录
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public Task<int> UpdateAsync(TEntity[] entities)
{
return Context.Updateable(entities).ExecuteCommandAsync();
}
/// <summary>
/// 更新多条记录指定列
/// </summary>
/// <param name="entities"></param>
/// <param name="updateColumn"></param>
/// <returns></returns>
public int Update(TEntity[] entities, object updateColumn)
{
return Context.Updateable(entities).UpdateColumns(MergeUpdateColumns(updateColumn)).ExecuteCommand();
}
/// <summary>
/// 更新多条记录指定列
/// </summary>
/// <param name="entities"></param>
/// <param name="updateColumn"></param>
/// <returns></returns>
public Task<int> UpdateAsync(TEntity[] entities, object updateColumn)
{
return Context.Updateable(entities).UpdateColumns(MergeUpdateColumns(updateColumn)).ExecuteCommandAsync();
}
/// <summary>
/// 合并指定更新列和附加更新列
/// </summary>
/// <param name="updateColumn"></param>
/// <returns></returns>
private string[] MergeUpdateColumns(object updateColumn)
{
List<string> columnList = new List<string>();
if (updateColumn.GetType() == typeof(string))
{
columnList.Add((string)updateColumn);
}
else if (updateColumn.GetType() == typeof(string[]))
{
columnList.AddRange((string[])updateColumn);
}
return columnList.ToArray();
}
#endregion
#region
/// <summary>
/// 删除一条记录
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public int Delete(object key)
{
return Context.Deleteable<TEntity>().In(key).ExecuteCommand();
}
/// <summary>
/// 删除一条记录
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public Task<int> DeleteAsync(object key)
{
return Context.Deleteable<TEntity>().In(key).ExecuteCommandAsync();
}
/// <summary>
/// 删除多条记录
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public int Delete(object[] keys)
{
return Context.Deleteable<TEntity>().In(keys).ExecuteCommand();
}
/// <summary>
/// 删除多条记录
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public Task<int> DeleteAsync(object[] keys)
{
return Context.Deleteable<TEntity>().In(keys).ExecuteCommandAsync();
}
#endregion
#region
/// <summary>
/// 开启事务
/// </summary>
public void BeginTran()
{
Context.Ado.BeginTran();
}
/// <summary>
/// 提交事务
/// </summary>
public void CommitTran()
{
Context.Ado.CommitTran();
}
/// <summary>
/// 回滚事务
/// </summary>
public void RollbackTran()
{
Context.Ado.RollbackTran();
}
#endregion
}
}

View File

@ -49,7 +49,9 @@ namespace ProcessManager.ViewModels
private void OnWindowLoaded()
{
if (ConfigList != null) ConfigList.Clear();
var JSONFiles = Directory.GetFiles(JsonHelper.SystemPath, "*.json");
var JSONFiles = Directory.GetFiles(JsonHelper.SystemPath, "*.json")
.Where(f => !f.EndsWith("UpdateInfo.json", StringComparison.OrdinalIgnoreCase))
.ToArray();
foreach (var file in JSONFiles)
{
JsonHelper.ConfigFile = file;

View File

@ -136,7 +136,7 @@
</MenuItem>
<MenuItem FontSize="14"
Height="50"
Header="环境箱和水冷机"
Header="水冷机和环境箱"
Foreground="White"
Command="{Binding DataContext.NavigateToDeviceCommand, RelativeSource={RelativeSource AncestorType=Window}}"
CommandParameter="Other">

View File

@ -0,0 +1,18 @@
using Model;
using Model.SQLModel;
using ORM;
using Service.Interface;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Service.Implement
{
public class BackFeedService : BaseService<BackFeedData>
{
public BackFeedService(SqlSugarRepository<BackFeedData> repository) : base(repository)
{
}
}
}

View File

@ -0,0 +1,92 @@
using Model;
using Model.SQLModel;
using ORM;
using Service.Interface;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Service.Implement
{
public class BaseService<TEntity> : IBaseService<TEntity> where TEntity : BaseEntity, new()
{
protected readonly SqlSugarRepository<TEntity> _repository;
public BaseService(SqlSugarRepository<TEntity> repository)
{
_repository = repository;
}
/// <summary>
/// 查询全部
/// </summary>
public async Task<Result<List<TEntity>>> GetAllAsync()
{
try
{
var list = await _repository.Entities.ToListAsync();
return Result<List<TEntity>>.Success(list);
}
catch (Exception ex)
{
return Result<List<TEntity>>.Error("查询所有数据失败", ex);
}
}
/// <summary>
/// 分页查询
/// </summary>
public async Task<Result<List<TEntity>>> GetPagedAsync(int pageIndex, int pageSize, RefAsync<int> total)
{
try
{
var list = await _repository.Entities
.OrderBy(d => d.Id)
.ToPageListAsync(pageIndex, pageSize, total);
total.Value = (int)Math.Ceiling((double)total.Value / pageSize);
return Result<List<TEntity>>.Success(list);
}
catch (Exception ex)
{
return Result<List<TEntity>>.Error("分页查询数据失败", ex);
}
}
/// <summary>
/// 分页查询,并可以根据日期范围进行过滤
/// </summary>
public async Task<Result<List<TEntity>>> GetPagedAsync(int pageIndex, int pageSize, RefAsync<int> total, DateTime? startDate, DateTime? endDate)
{
try
{
var list = await _repository.Entities
.Where(x=>x.CollectTime>=startDate&&x.CollectTime<=endDate)
.OrderBy(d => d.Id)
.ToPageListAsync(pageIndex, pageSize, total);
total.Value = (int)Math.Ceiling((double)total.Value / pageSize);
return Result<List<TEntity>>.Success(list);
}
catch (Exception ex)
{
return Result<List<TEntity>>.Error("分页查询数据失败", ex);
}
}
/// <summary>
/// 插入单条数据
/// </summary>
public async Task<Result<bool>> InsertAsync(TEntity entity)
{
try
{
var result = await _repository.Context.Insertable(entity).ExecuteCommandAsync();
return Result<bool>.Success(result > 0);
}
catch (Exception ex)
{
return Result<bool>.Error("插入数据失败", ex);
}
}
}
}

View File

@ -0,0 +1,18 @@
using Model.SQLModel;
using ORM;
using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Implement
{
public class EAEL9080Service : BaseService<EAELD9080Data>
{
public EAEL9080Service(SqlSugarRepository<EAELD9080Data> repository) : base(repository)
{
}
}
}

View File

@ -0,0 +1,17 @@
using Model.SQLModel;
using ORM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Implement
{
public class IT6724CService : BaseService<IT6724CData>
{
public IT6724CService(SqlSugarRepository<IT6724CData> repository) : base(repository)
{
}
}
}

View File

@ -0,0 +1,17 @@
using Model.SQLModel;
using ORM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Implement
{
public class LQ7500DService : BaseService<LQ7500Data>
{
public LQ7500DService(SqlSugarRepository<LQ7500Data> repository) : base(repository)
{
}
}
}

View File

@ -0,0 +1,17 @@
using Model.SQLModel;
using ORM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Implement
{
public class PSB11000Service : BaseService<PSB1100Data>
{
public PSB11000Service(SqlSugarRepository<PSB1100Data> repository) : base(repository)
{
}
}
}

View File

@ -0,0 +1,17 @@
using Model.SQLModel;
using ORM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Implement
{
public class SQ0030Service : BaseService<SQ0030Data>
{
public SQ0030Service(SqlSugarRepository<SQ0030Data> repository) : base(repository)
{
}
}
}

View File

@ -0,0 +1,17 @@
using Model.SQLModel;
using ORM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Implement
{
public class WS680Service : BaseService<WS680Data>
{
public WS680Service(SqlSugarRepository<WS680Data> repository) : base(repository)
{
}
}
}

View File

@ -0,0 +1,18 @@
using Model.SQLModel;
using ORM;
using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Implement
{
public class ZXKXService : BaseService<ZXKSData>
{
public ZXKXService(SqlSugarRepository<ZXKSData> repository) : base(repository)
{
}
}
}

View File

@ -0,0 +1,48 @@
using Model;
using Model.SQLModel;
using SqlSugar;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Service.Interface
{
/// <summary>
/// 泛型基础服务接口(返回 Result 封装)
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
public interface IBaseService<TEntity> where TEntity : class, new()
{
/// <summary>
/// 查询全部
/// </summary>
/// <returns>返回包含数据的 Result</returns>
Task<Result<List<TEntity>>> GetAllAsync();
/// <summary>
/// 插入单条数据
/// </summary>
/// <param name="entity"></param>
/// <returns>返回操作是否成功的 Result</returns>
Task<Result<bool>> InsertAsync(TEntity entity);
/// <summary>
/// 分页查询
/// </summary>
/// <param name="pageIndex">页码从1开始</param>
/// <param name="pageSize">每页数量</param>
/// <param name="total">总条数(输出参数)</param>
/// <returns>返回包含分页数据的 Result</returns>
Task<Result<List<TEntity>>> GetPagedAsync(int pageIndex, int pageSize, RefAsync<int> total);
/// <summary>
/// 分页查询,并根据日期范围进行过滤
/// </summary>
/// <param name="pageIndex">页码从1开始</param>
/// <param name="pageSize">每页数量</param>
/// <param name="total">总条数(输出参数)</param>
/// <param name="startDate">开始日期</param>
/// <param name="endDate">结束日期</param>
/// <returns>返回包含分页数据的 Result</returns>
Task<Result<List<TEntity>>> GetPagedAsync(int pageIndex, int pageSize, RefAsync<int> total, DateTime? startDate, DateTime? endDate);
}
}

View File

@ -12,6 +12,7 @@
<ItemGroup>
<ProjectReference Include="..\Logger\Logger.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
<ProjectReference Include="..\ORM\ORM.csproj" />
</ItemGroup>