Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework, can I map a class to a key/value table?

In my Database, I have a key/value table, which I use to store the configuration of the application. Some example settings of the StoreConfiguration class, that I want to map to this key/value table.

 public class StoreConfiguration
 {

    //.... more settings

    public int DefaultPartnerID { get; set; }

    public int DefaultOperatorID { get; set; }

    public string DefaultCurrency { get; set; }

    public int DefaultCurrencyID { get; set; }

    //.... more settings

I would like to have those in my DataBase as this for example

Key               | Value
--------------------------
DefaultpartnerID  | 1
DefaultOperatorID | 10
DefaultCurrency   | USD
DefaultCurrencyID | 2

Is it possible to create such type of mapping with EntityFramework ?

like image 556
Shtiliyan Uzunov Avatar asked Dec 20 '22 12:12

Shtiliyan Uzunov


1 Answers

You might want to use a simple entity that contains Key and Value property.

public class StoreConfiguration
{
    [Key]
    public string Key { get; set; }
    public string Value { get; set; }
}

Then provide an extension to add and remove the store configuration.

public static class StoreConfigurationExtension
{
    public static T GetStoreConfiguration<T>(this DbContext db, string key)
    {
        var sc = db.Set<StoreConfiguration>().Find(key);
        if (sc == null) return default(T);

        var value = sc.Value;
        var tc = TypeDescriptor.GetConverter(typeof(T));
        try
        {
            var convertedValue = (T)tc.ConvertFromString(value);
            return convertedValue;
        }
        catch (NotSupportedException)
        {
            return default(T);
        }
    }

    public static void SetStoreConfiguration(this DbContext db, string key, object value)
    {
        var sc = db.Set<StoreConfiguration>().Find(key);
        if (sc == null)
        {
            sc = new StoreConfiguration { Key = key };
            db.Set<StoreConfiguration>().Add(sc);
        }

        sc.Value = value == null ? null : value.ToString();
    }
}

Usage.

using (var db = new AppContext())
{
    db.SetStoreConfiguration("DefaultpartnerID", 1);
    db.SaveChanges();
}
using (var db = new AppContext())
{
    var defaultpartnerID = db.GetStoreConfiguration<int>("DefaultpartnerID");
    db.SaveChanges();
}
like image 127
Yuliam Chandra Avatar answered Dec 27 '22 01:12

Yuliam Chandra