/// <summary> /// Gets the redis key for the specified entity based upon the redis entity mappings. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entity"></param> /// <returns></returns> public static string GetKey <T>(T entity = null) where T : class { // Make sure the mappings have been loaded for this type. RedisEntityMapping mapping = LoadMapping(typeof(T)); // Start with the primary key. StringBuilder key = new StringBuilder(mapping.PrimaryKey); // Append a secondary key if there is one. if (!String.IsNullOrWhiteSpace(mapping.SecondaryKey)) { key.Append(":").Append(mapping.SecondaryKey); } // Append the value of each key property. if (entity != null) { foreach (RedisKeyMapping keyProperty in mapping.KeyProperties.OrderBy(k => k.Order)) { key.Append(":").Append(keyProperty.PropertyInfo.GetValue(entity).ToString()); } } return(key.ToString()); }
/// <summary> /// Loads all of the entities of a specified type. /// </summary> /// <typeparam name="ENTITY"></typeparam> /// <param name="client"></param> /// <returns></returns> public static List <ENTITY> GetAll <ENTITY>(IRedisClient <string> client) where ENTITY : class { // Make sure the mappings have been loaded for this type. RedisEntityMapping mapping = LoadMapping(typeof(ENTITY)); List <ENTITY> list = new List <ENTITY>(); foreach (KeyValuePair <string, string> item in client.HGetAll(GetKey <ENTITY>())) { list.Add(JsonSerializer.DeserializeObject(item.Value, typeof(ENTITY)) as ENTITY); } return(list); }
/// <summary> /// Inserts an entity into Redis. /// </summary> /// <typeparam name="ENTITY"></typeparam> /// <param name="entity"></param> /// <returns></returns> public static ENTITY Insert <ENTITY>(IRedisClient <string> client, ENTITY entity) where ENTITY : class { // Make sure the mappings have been loaded for this type. RedisEntityMapping mapping = LoadMapping(typeof(ENTITY)); // If the field property is a sequence, get the next sequence value. if (mapping.FieldProperty != null && mapping.FieldProperty.IsSequence) { mapping.FieldProperty.PropertyInfo.SetValue(entity, (int)client.Incr(String.Format("seq:{0}", typeof(ENTITY).Name))); } // Set the value in redis. client.HSet(GetKey(entity), GetField(entity), JsonSerializer.SerializeObject(entity)); return(entity); }