使用 Cosmos db 通过 EF Core 8 保存 JsonElement 返回未定义

问题描述 投票:0回答:1

我将 EF Core 8 与 CosmosDb 结合使用,并且我正在保存

Dictionary<string, JsonElement>
,我认为数据已保存。

{
    "id": "7015e3d9-d300-4bb6-f441-08dc57de0ee3",
    "Data": {
        "Identifier": {
            "ValueKind": 3
        }
    },
    "Description": "TestApplicationName_7ef73a36-1187-4c41-b999-5d8fa7d0cc89",
...
}

当我在

GetData
之后调用
SaveData
时,该值就在那里(可能来自缓存),如果是在其他调用中,例如 API HttpPost / HttpGet,则该值是

enter image description here

ValueKind = Undefined : ""

所有其他值都是正确的,包括字典键,只有

JsonElement
未定义。

我做错了什么?

public class Data
{
    public Guid Id { get; set; }
    public string Description { get; set; } = string.Empty;

    public Dictionary<string, JsonElement> Data { get; set; } = [];
}

保存方法:

    public async Task<Guid?> AddData(Data data, CancellationToken cancellationToken)
    {
        var addDataResult = _context.Data.Add(data);

        try
        {
            int result = await _context.SaveChangesAsync(cancellationToken);

            if (result > 0)
            {
                return addDataResult.Entity.DataId;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError("(Exception) Adding Data: {application.ApplicationId}, message: {ex.Message}", data.DataId, ex.Message);
        }

        return null;
    }

加载方式:

    public async Task<Data?> GetData(Guid dataId, CancellationToken cancellationToken)
    {
        Data? data= await _context.Data.FindAsync([dataId], cancellationToken);

        if (data is not null)
        {
            return data;
        }

        return null;
    }

提前致谢。

c# azure-cosmosdb .net-8.0 ef-core-8.0
1个回答
0
投票

使用 Cosmos db 通过 EF Core 8 保存 JsonElement 返回未定义

显示未定义的原因可能是由于在要保存在 Azure Cosmos DB 容器中的数据中提供了 id 值,并且在

Data
类中它被定义为
GUID
。当它是
GUID
时,该值将在将数据存储到容器中时自行生成唯一标识符。尝试使用以下代码成功将数据保存在 Azure Cosmos DB 容器中,并检索保存的数据,如下面的输出所示。

public class Data
    {
        public Guid id { get; set; }
        public string Description { get; set; } = string.Empty;

        public Dictionary<string, string> DataValues { get; set; } = new Dictionary<string, string>();

        public void AddJsonElement(string key, JsonElement value)
        {
            DataValues[key] = value.ToString();
        }

        public JsonElement GetJsonElement(string key)
        {
            if (DataValues.TryGetValue(key, out string value))
            {
                return JsonDocument.Parse(value).RootElement;
            }
            else
            {
                return default(JsonElement);
            }
        }
    }

    public class ApplicationDbContext : DbContext
    {
        public DbSet<Data> Data { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Data>()
                .ToContainer("newCont2") 
                .HasPartitionKey(d => d.id); 
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseCosmos("<connectionString>", "newDb");
        }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder.AddConsole();
            });
            var logger = loggerFactory.CreateLogger<Program>();

            try
            {
                using (var context = new ApplicationDbContext())
                {
                    var testData = new Data
                    {
                        id = Guid.NewGuid(),
                        Description = "Test description",
                        DataValues = new Dictionary<string, string>
                        {
                            { "Key1", "{\"Value\": 42}" }, 
                            { "Key2", "{\"Name\": \"John\"}" } 
                        }
                    };

                    await context.Data.AddAsync(testData);
                    await context.SaveChangesAsync();

                    var retrievedData = await context.Data.FirstOrDefaultAsync();

                    if (retrievedData != null)
                    {
                        Console.WriteLine("Retrieved data:");
                        Console.WriteLine($"Id: {retrievedData.id}");
                        Console.WriteLine($"Description: {retrievedData.Description}");

                        foreach (var kvp in retrievedData.DataValues)
                        {
                            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
                        }
                    }
                    else
                    {
                        Console.WriteLine("No data found.");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"An error occurred: {ex.Message}");
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
    }

输出:

Retrieved data:
Id: 29e87f3a-9dd1-4f55-9ec0-507bd2d1bb51
Description: Test description
Key: Key1, Value: {"Value": 42}
Key: Key2, Value: {"Name": "John"}
Press any key to exit...

Azure Cosmos DB 容器中保存的数据: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.