-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRunningDataService.cs
69 lines (60 loc) · 2.25 KB
/
RunningDataService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System.Data.SQLite;
using System.IO;
using Dapper;
using Dapper.Contrib.Extensions;
namespace RunningLog;
internal class RunningDataService
{
public string DataDir { get; set; }
private readonly string _conStr;
public RunningDataService(string dataDir)
{
DataDir = dataDir;
string dbPath = Path.Combine(DataDir, "RunningLog.db");
_conStr = $"Data Source={dbPath};Version=3;";
}
public Dictionary<DateTime, List<RunData>> LoadData(int year)
{
using (var connection = new SQLiteConnection(_conStr))
{
connection.Open();
var startDate = new DateTime(year, 1, 1);
var endDate = new DateTime(year + 1, 1, 1); // 下一年的1月1日
var data = connection.Query<RunData>("SELECT * FROM RunData WHERE Date >= @StartDate AND Date < @EndDate", new { StartDate = startDate.ToString("yyyy-MM-dd"), EndDate = endDate.ToString("yyyy-MM-dd") })
.GroupBy(r => r.Date)
.ToDictionary(g => g.Key, g => g.ToList());
return data;
}
}
public int Save(RunData runData)
{
using (var connection = new SQLiteConnection(_conStr))
{
connection.Open();
var lastInsertedId = (int)connection.Insert(runData); // 返回新插入记录的ID
return lastInsertedId;
}
}
public bool DoesYearHasData(int year)
{
using (var connection = new SQLiteConnection(_conStr))
{
connection.Open();
var startDate = new DateTime(year, 1, 1);
var endDate = new DateTime(year + 1, 1, 1); // 下一年的1月1日
var c = connection.ExecuteScalar<int>(
"SELECT count(*) FROM RunData WHERE Date >= @StartDate AND Date < @EndDate",
new { StartDate = startDate.ToString("yyyy-MM-dd"), EndDate = endDate.ToString("yyyy-MM-dd") });
return c > 0;
}
}
public async Task<bool> Delete(int lastInsertedId)
{
await using (var connection = new SQLiteConnection(_conStr))
{
connection.Open();
var runDataToDelete = new RunData { Id = lastInsertedId };
return await connection.DeleteAsync(runDataToDelete);
}
}
}