gpt4 book ai didi

c# - Entity Framework ,我可以将一个类映射到一个键/值表吗?

转载 作者:搜寻专家 更新时间:2023-10-30 19:57:38 24 4
gpt4 key购买 nike

在我的数据库中,我有一个键/值表,用于存储应用程序的配置。我想映射到此键/值表的 StoreConfiguration 类的一些示例设置。

 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

例如,我希望在我的数据库中有这些

Key               | Value--------------------------DefaultpartnerID  | 1DefaultOperatorID | 10DefaultCurrency   | USDDefaultCurrencyID | 2

是否可以使用 EntityFramework 创建此类映射?

最佳答案

您可能希望使用包含 KeyValue 属性的简单实体。

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

然后提供一个扩展来添加和删除商店配置。

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();
}
}

用法。

using (var db = new AppContext())
{
db.SetStoreConfiguration("DefaultpartnerID", 1);
db.SaveChanges();
}
using (var db = new AppContext())
{
var defaultpartnerID = db.GetStoreConfiguration<int>("DefaultpartnerID");
db.SaveChanges();
}

关于c# - Entity Framework ,我可以将一个类映射到一个键/值表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25420477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com