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 ?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With