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.
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);
StackExchange.Redis is a raw client - it talks in Redis terms only. It does not attempt to be an ORM of any kind. It will, however, store any string
or byte[]
that you care to throw at it - which means you should have your choice of serializers. JSON would be a reasonable default (Jil is awesome), although we tend to use protocol-buffers ourselves (via protobuf-net).
It you intend to use list semantics, I strongly recommend starting with the List* commands - sets have different semantics to lists - sets are unordered and only store unique values; lists preserve order and allow duplicates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With