-
Notifications
You must be signed in to change notification settings - Fork 34
/
SettingRepository.cs
95 lines (75 loc) · 2.62 KB
/
SettingRepository.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Asp.Core.Domains;
using Asp.Data;
using Microsoft.Extensions.Caching.Memory;
namespace Asp.Repositories.Settings
{
public class SettingRepository : ISettingRepository
{
private const string SettingsAllKey = "setting.all";
private readonly IDbContext _context;
private readonly IMemoryCache _cache;
public SettingRepository(IDbContext context, IMemoryCache cache)
{
_context = context;
_cache = cache;
}
public Setting GetSettingById(int settingId)
{
if (settingId == 0)
return null;
var query = _context.Settings
.Where(b => b.Id == settingId);
return query.FirstOrDefault();
}
public string GetSettingByKey(string key, string defaultValue)
{
if (string.IsNullOrWhiteSpace(key))
return defaultValue;
var settings = GetAllSettings();
key = key.Trim().ToLowerInvariant();
var setting = settings.FirstOrDefault(x => x.Name == key);
if (setting != null)
return setting.Value;
return defaultValue;
}
public T GetSettingByKey<T>(string key, T defaultValue)
{
if (string.IsNullOrWhiteSpace(key))
return defaultValue;
var settings = GetAllSettings();
key = key.Trim().ToLowerInvariant();
var setting = settings.FirstOrDefault(x => x.Name == key);
if (setting != null)
return (T) Convert.ChangeType(setting.Value, typeof (T));
return defaultValue;
}
public IList<Setting> GetAllSettings()
{
string key = string.Format(SettingsAllKey);
IList<Setting> setting = null;
if (!_cache.TryGetValue(key, out setting))
{
setting = _context.Settings
.OrderBy(s => s.Name)
.ToList();
var options = new MemoryCacheEntryOptions().SetSlidingExpiration(Core.Constants.CacheTimes.DefaultTimeSpan);
_cache.Set(key, setting, options);
}
return setting;
}
public void ClearCache()
{
_cache.Remove(SettingsAllKey);
}
public async Task UpdateSettingAsync(Setting setting)
{
_context.Settings.Update(setting);
await _context.SaveChangesAsync();
_cache.Remove(SettingsAllKey);
}
}
}