【问题标题】:Getting database constants and storing them in cache获取数据库常量并将它们存储在缓存中
【发布时间】:2011-10-12 10:30:38
【问题描述】:

项目信息:WPF、PRISM、C# 4.0、WCF、实体框架、SQL(express)

我的数据库包含几个“常量”,例如一个人有一个分类 -> 自然人 (ID = 1) 或合法人 (ID = 2)。

我想从数据库中取出这些常量,并将它们存储在缓存中,这样它们就可以在整个应用程序中使用,因此它们不是“硬编码”的。我知道您可以将这些常量存储在静态类中,但这只有在数据库中的这些常量不发生变化时才有效(而且我不想依赖这个事实)。

我的问题是:如何有效地从数据库中加载这些常量并将它们放入我的缓存中?

以下是我现在的写法,但是感觉不对..

using (DetacheringenEntities objectcontext = new DetacheringenEntities())
{
   int natuurlijkPersoonClassificationResult = objectcontext.Classification.Where(c => c.Value == "Natuurlijk Persoon").Select(c => c.ClassificationID).SingleOrDefault();
   int rechtspersoonPersoonClassificationResult = objectcontext.Classification.Where(c => c.Value == "Rechtspersoon").Select(c => c.ClassificationID).SingleOrDefault();

   int klantPersonAgreementRoleResult = objectcontext.PersonAgreementInvolvementRole.Where(p => p.Value == "Klant").Select(p => p.PersonAgreementInvolvementRoleID).SingleOrDefault();  
   ... (about 10 more of these calls)    
}

将这些从数据库中取出后,我将它们放入缓存中:

 DefaultCacheProvider cacheProvider = new DefaultCacheProvider();
 cacheProvider.Set("NatuurlijkPersoon", natuurlijkPersoonClassificationResult, 30);

我在缓存上使用了一个存储库,所以我也可以稍后进行单元测试。

我尝试过制作一个通用的方法,但我失败了:P

private int GetDatabaseConstantValue<T>(Expression<Func<T, bool>> expression, DetacheringenEntities context)
{
        int result = context
            .CreateQuery<T>(
            "[" + typeof(T).Name + "]")
            .Where(expression)
            .Select(typeof(T).Name + "ID").FirstOrDefault(); --> This doesn't work (obviously), but I want to select the ID of that table (which is always Tablename + ID).

        return result;
}

有什么想法可以解决这个问题或让它变得更好吗?

感谢您的帮助!!

PS:任何提示也很感激:)

【问题讨论】:

  • 文本值“Natuurlijk Persoon”不是比它的ID号更容易改变吗?

标签: c# database generics caching constants


【解决方案1】:

你就不能建立一个字典吗?

var classifications = objectcontext.Classification.ToDictionary(c => c.Value, c => c.ClassificationID);

然后就可以取回值了:

classifications["Natuurlijk Persoon"]

【讨论】:

  • 感谢您的回复,但是如何跨多个解决方案访问“分类”?我有一个管理我的 WCF 解决方案的“管理器解决方案”,在这个管理器解决方案中我想启动常量。当我使用这本词典时,我可以在“子”解决方案之一中使用它吗?谢谢。顺便说一句:字典就是我要找的,我可以把字典放在我的缓存里吗?
  • 您应该可以将字典放入缓存中。一旦它在字典中,它就与任何其他 C# 对象相同,并且没有与数据库的连接等。至于跨多个解决方案访问,这取决于您的代码...
  • 如果我可以将它放在我的缓存中,那么我可以访问它:) 非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2012-02-22
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 1970-01-01
相关资源
最近更新 更多