내 데이터베이스에는 애플리케이션 구성을 저장하는 데 사용하는 키 / 값 테이블이 있습니다. 이 키 / 값 테이블에 매핑하려는 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
예를 들어 내 데이터베이스에 이것들이 있고 싶습니다.
키 | 값 -------------------------- DefaultpartnerID | 1 DefaultOperatorID | 10 DefaultCurrency | USD DefaultCurrencyID | 2
EntityFramework로 이러한 유형의 매핑을 만들 수 있습니까?
Key
및 Value
속성 을 포함하는 간단한 엔터티를 사용할 수 있습니다 .
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();
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다