Natural Person (ID = 1) or lawful person (ID = 2" />
开发者

Getting database constants and storing them in cache

开发者 https://www.devze.com 2023-04-12 16:54 出处:网络
Project info: WPF, PRISM, C# 4.0, WCF, Entity framework, SQL(express) My database contains several \"constants\" e.g. a person has a classification -> Natural Person (ID = 1) or lawful person (ID = 2

Project info: WPF, PRISM, C# 4.0, WCF, Entity framework, SQL(express)

My database contains several "constants" e.g. a person has a classification -> Natural Person (ID = 1) or lawful person (ID = 2).

I want to get these constants out of the DB, and store them in the cache, so they can be used throughout the application, so they aren't "hard coded". I know you can store these constants in a static 开发者_C百科class, but this would only work if these constants don't change in the DB (and I don't want to rely on that fact).

My question is: how can I efficiently load these constants out of the DB and put them in my cache?

The following is how I've written it now, but it just doesn't feel right..

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

After getting these out of the DB I put them in my cache:

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

I make use of a Repository on my caching, so I can also unit test is later.

I've tried making a generic methode, but I failed terribly :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;
}

Any ideas of how I can solve this problem or make it better?

Thanks for any help!!

PS: Any tips are also appreciated :)


Can't you just build a dictionary?

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

Then you can retrieve the value:

classifications["Natuurlijk Persoon"]
0

精彩评论

暂无评论...
验证码 换一张
取 消