Creating property value cache manager

  • Thread starter Thread starter Andrus
  • Start date Start date
A

Andrus

I need to create Dlinq entity property value caches for every entity and
every property so that
all entity caches can cleared if entity of this type is changed. Entity
class method uses this as:

string GetCustomerNameById( string customerId ) {
var cache = CacheManager.Get<Customer,string, string>("CustomerName");
string res;
if (cache.TryGetValue(customerId , out res))
return res;
res = Nowthwind.Customers.Where(x => x.CustomerId == customerId).Select(x
=> x.CustomerName.Single();
cache.Add(customerId , res);
return res;
}

If customer has changed, I call

CacheManager.Clear( typeof(Customer) );

I created class below but got "Type expected" compile error in line shown in
comment.
How to fix ?

Andrus.

using System;
using System.Collections.Generic;

namespace Eetasoft.Eeva.Entity
{
public static class CacheManager
{
struct Key
{
internal Type Entity;
internal string Property;
}

// this causes compile errror: type expected
static Dictionary<Key, Dictionary<,>> CacheList = new
Dictionary<Key, Dictionary<,>>();

/// <summary>
/// Gets existing or creates new property cache.
/// </summary>
public static Dictionary<TKey, TValue> Get<TEntity,TKey,
TValue>(string propertyName)
{
var key = new Key() { Entity = typeof(TEntity), Property =
propertyName };
Dictionary<TKey, TValue> cache;
if (CacheList.TryGetValue(key, out cache))
return cache;
cache = new Dictionary<TKey, TValue>();
CacheList.Add(key, cache);
return cache;
}

/// <summary>
/// Clear the cache if entity has changed.
/// </summary>
/// <param name="entity"></param>
public static void Clear(Type entity)
{
foreach (var key in CacheList.Keys)
{
if (key.Entity == entity)
CacheList.Remove(key);
}
}
}
}
 
The open-type syntax (Dictionary<,>) is only valid in the context of
typeof(), usually in anticipation of MakeGenericType(). It is not
legal for a field/variable, which must use a closed-type, such as
Dictionary<string,object>.

Marc
 
Back
Top