Shawn Mclean
Shawn Mclean

Reputation: 57469

Storing system settings and configurations for a website in a database?

How do I structure the database? I use a repository pattern with entity framework and code-first to code the models.

For example: I want an admin to set a string to be appended to every username.

I was thinking about a key-value table (settings) that has the following columns? SettingsId, Name, Value. With this method, I would need to manually go in, create a record Name:AppendedToUsername, Value:nil. I would then write repository methods specifically for each settings I need. For eg.

public string GetAppenedToUsername()
{
    db.Settings.FirstOrDefault(s => s.Name == "AppendedToUsername").Select(s => s.Value);
}

Is there any better way of designing this database?

Upvotes: 2

Views: 141

Answers (1)

Andrei Schneider
Andrei Schneider

Reputation: 3563

It's a good solution. I only recommend to create a strongly typed class with these settings and use caching for them.

Cache service:

 public class CacheService
    {
        private ObjectCache Cache
        {
            get { return MemoryCache.Default; }
        }

        public object Get(string key)
        {
            return Cache[key];
        }

        public void Set(string key, object data, int cacheTime)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now.AddMinutes(cacheTime);

            Cache.Add(new CacheItem(key, data), policy);
        }

        public bool IsSet(string key)
        {
            return (Cache[key] != null);
        }

        public void Invalidate(string key)
        {
            Cache.Remove(key);
        }
    }

AppSetting:

public class AppSetting
{
    public const string StrSettingKey = "StrSetting";

    private CacheService CacheService { get; set; }
    private DbContext DbContext { get; set; }

    public AppSetting(ICacheService cache, DbContext db)
    {
        CacheService = CacheService;
        DbContext = db;
    }

    public string StrSetting
    {
        get
        {
            if (CacheService.IsSet(StrSettingKey))
            {
                return (string) CacheService.Get(StrSettingKey);
            }
            else
            {
                var value = DbContext.Settings.Single(s => s.Name == StrSettingKey).Select(s => s.Value);
                CacheService.Set(StrSettingKey, value, 60); //one hour
                return value;
            }

        }
        set
        {

            var item = DbContext.Settings.Single(s => s.Name == StrSettingKey);
            item.Value = value;
            DbContext.SaveChanges();
            CacheService.Set(StrSettingKey, value);

        }
    }

}

Upvotes: 1

Related Questions