Skip to content

How to update nested collection #541

@Jimmys20

Description

@Jimmys20

Hello, I'm trying to update a nested collection using new List but the new items are concatenated with the already existing items. Is this supported by Redis and Redis.OM? Here is a small demo of what I'm trying to do. Am I doing something wrong?

[Document(StorageType = StorageType.Json, Prefixes = ["Player"])]
public class PlayerEntity
{
  [RedisIdField, Indexed] public string UniquePlayerId { get; set; }

  public IEnumerable<ReportItem> ReportItems { get; set; }
}

public class ReportItem
{
  public string Caption { get; set; }
  public double Value { get; set; }
}

internal class Program
{
  static async Task Main(string[] args)
  {
    var redisConfigurationOptions = new StackExchange.Redis.ConfigurationOptions
    {
      EndPoints = { "192.168.100.4:6379" },
      User = null,
      Password = null,
      AllowAdmin = false,
      Ssl = false,
    };

    var provider = new RedisConnectionProvider(redisConfigurationOptions);

    provider.Connection.DropIndexAndAssociatedRecords(typeof(PlayerEntity));
    await provider.Connection.CreateIndexAsync(typeof(PlayerEntity));

    var players = provider.RedisCollection<PlayerEntity>();

    await players.InsertAsync(new PlayerEntity
    {
      UniquePlayerId = "some-unique-id",
      ReportItems = new List<ReportItem>
      {
        new ReportItem { Caption = "Score", Value = 100 },
        new ReportItem { Caption = "Time Played", Value = 3600 }
      }
    });

    var player = await players.FirstOrDefaultAsync(p => p.UniquePlayerId == "some-unique-id");
    Console.WriteLine("Count: " + player.ReportItems.Count()); // Count: 2

    player.ReportItems = new List<ReportItem>
    {
      new ReportItem { Caption = "Score", Value = 200 },
      new ReportItem { Caption = "Time Played", Value = 7200 }
    };

    await players.UpdateAsync(player);

    var updatedPlayer = await players.FirstOrDefaultAsync(p => p.UniquePlayerId == "some-unique-id");
    Console.WriteLine("Updated Count: " + updatedPlayer.ReportItems.Count()); // Updated Count: 4
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions