STRHM
1.0.0
介紹文章
範例實體是一個 Book 類,它有幾個基本欄位。
public class Book
{
public int Id { get; set; }
public int? Rating { get; set; }
public DateTime PublishedOn { get; set; }
[SerializableRedisProperty]
public List<Author> Authors { get; set; }
}
沒錯,您注意到了一個自訂屬性。此屬性負責將特定屬性作為值設定到 Redis 哈希時進行序列化。
Book 儲存庫繼承自 BaseRedisHashSetRepository,因為它公開了最常見的所需功能和資料庫連接,以防您想擴展 Book 儲存庫本身的功能。
public class BookRepository : BaseRedisHashSetRepository<Book>
{
public BookRepository(IRedisConnection redisConnection, IStronglyTypedRedisSerializer serializer, RedisHashSetOptions configurationOptions)
: base(redisConnection, serializer, configurationOptions)
{
}
}
建構函數參數:
取得值的範例:
// Check if value is set on property
if (updatedBook.HasValue(b => b.Rating))
// Get values
updatedBook.Get<IEnumerable<Author>>(b => b.Authors)
updatedBook.Get<int?>(b => b.Rating)
或者
var book = await _bookRepository.GetAsync(book.Id.ToString());
設定值範例:
await _bookRepository.SaveAsync(book.Id.ToString(), book);
或者
await _bookRepository.HashSetAsync(book.Id.ToString(), new StronglyTypedDictionary<Book>(new StronglyTypedRedisNewtonsoftSerializer())
{
{ b => b.Rating, 10 },
{ b => b.Authors, new List<Author>()},
{ b => b.PublishedOn, DateTime.Now }
});