Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 1d6cdd9

Browse files
committed
Allow StoreAsHash behavior to be overridden
1 parent 1499e81 commit 1d6cdd9

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

src/ServiceStack.Redis/RedisClient.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ public RedisClient()
4242

4343
public static Func<RedisClient> NewFactoryFn = () => new RedisClient();
4444

45+
public static Func<object, Dictionary<string, string>> ConvertToHashFn =
46+
x => x.ToJson().FromJson<Dictionary<string, string>>();
47+
4548
/// <summary>
4649
/// Creates a new instance of the Redis Client from NewFactoryFn.
4750
/// </summary>
@@ -736,7 +739,8 @@ public T GetFromHash<T>(object id)
736739
public void StoreAsHash<T>(T entity)
737740
{
738741
var key = UrnKey(entity);
739-
SetRangeInHash(key, entity.ToJson().FromJson<Dictionary<string, string>>());
742+
var hash = ConvertToHashFn(entity);
743+
SetRangeInHash(key, hash);
740744
RegisterTypeId(entity);
741745
}
742746

tests/ServiceStack.Redis.Tests/RedisClientHashTests.cs

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
using System.Collections.Generic;
33
using NUnit.Framework;
44
using ServiceStack.Common;
5+
using ServiceStack.Common.Tests.Models;
6+
using ServiceStack.Redis.Tests.Generic;
7+
using ServiceStack.Text;
58

69
namespace ServiceStack.Redis.Tests
710
{
@@ -268,6 +271,35 @@ public void Can_hash_multi_set_and_get()
268271
}
269272
}
270273

271-
}
274+
public class HashTest
275+
{
276+
public int Id { get; set; }
277+
public string Name { get; set; }
278+
}
279+
280+
[Test]
281+
public void Can_store_as_Hash()
282+
{
283+
var dto = new HashTest { Id = 1 };
284+
Redis.StoreAsHash(dto);
285+
286+
var storedHash = Redis.GetHashKeys(dto.ToUrn());
287+
Assert.That(storedHash, Is.EquivalentTo(new[] { "Id" }));
288+
289+
var hold = RedisClient.ConvertToHashFn;
290+
RedisClient.ConvertToHashFn = o =>
291+
{
292+
var map = new Dictionary<string, string>();
293+
o.ToObjectDictionary().Each(x => map[x.Key] = (x.Value ?? "").ToJsv());
294+
return map;
295+
};
296+
297+
Redis.StoreAsHash(dto);
298+
storedHash = Redis.GetHashKeys(dto.ToUrn());
299+
Assert.That(storedHash, Is.EquivalentTo(new[] { "Id", "Name" }));
300+
301+
RedisClient.ConvertToHashFn = hold;
302+
}
303+
}
272304

273305
}

0 commit comments

Comments
 (0)