How to add Generic List to Redis via StackExchange.Redis?

Shane picture Shane · Sep 17, 2014 · Viewed 22.1k times · Source

For example, if I have a model called Customer

public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address1 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
    }

Example:

var customers = new List<Customer>();

How would I added a List of Customer? How would I do this?

 using (var redis = ConnectionMultiplexer.Connect(this.redisServer))
            {
                var db = redis.GetDatabase();

                db.SetAdd(key, ?????);
}

I think SetAdd is the right method, but I can't see how to get my generic list of Customer (i.e. List into the format of RedisValue.

Answer

Andrey Gubal picture Andrey Gubal · Nov 9, 2014

May be it helps. I also faced the same question at the beginning of my diving into StackExchange.Redis. In my project I created 2 extension methods, which help me serialize/deserialize complex type for Redis database. You may extend them to your needs.

Methods:

    public static class RedisUtils
        {
//Serialize in Redis format:
            public static HashEntry[] ToHashEntries(this object obj)
            {
                PropertyInfo[] properties = obj.GetType().GetProperties();
                return properties.Select(property => new HashEntry(property.Name, property.GetValue(obj).ToString())).ToArray();
            }
    //Deserialize from Redis format
            public static T ConvertFromRedis<T>(this HashEntry[] hashEntries)
            {
                PropertyInfo[] properties = typeof(T).GetProperties();
                var obj = Activator.CreateInstance(typeof(T));
                foreach (var property in properties)
                {
                    HashEntry entry = hashEntries.FirstOrDefault(g => g.Name.ToString().Equals(property.Name));
                    if (entry.Equals(new HashEntry())) continue;
                    property.SetValue(obj, Convert.ChangeType(entry.Value.ToString(), property.PropertyType));
                }
                return (T)obj;
            }
        }

Usage:

var customer = new Customer
{
//Initialization
};

Db.HashSet("customer", customer.ToHashEntries());
Customer result = Db.HashGetAll("customer").ConvertFromRedis<Customer>();

Assert.AreEqual(customer.FirstName, result.FirstName);
Assert.AreEqual(customer.LastName, result.LastName);
Assert.AreEqual(customer.Address1, result.Address1);