使用 Entity Framework Core ExecuteSqlRawAsync 存储 Jsonstring

Vik*_*hra 5 c# entity-framework-core .net-core

我有一个实体,对于其中一个字符串字段,我想使用 EF CoreExecuteSqlRawAsync扩展存储 jsonstring(相当于 MyObject 列表的 json)。

但是,我收到此错误:

输入字符串的格式不正确。

从 EF 出发

Microsoft.EntityFrameworkCore.Storage.Internal.RawSqlCommandBuilder.Build。

我使用的是 EF Core 3.1 版本。

请在下面找到与我正在尝试的类似的示例概述:

string query = "update mytable set column1 = 100, column2= '[{\"property1\":\"value1\",\"property2\":null}]' where condition;update mytable set column1= 200, column2= '[{\"property1\":\"value2\",\"property\":null}]' where condition;"

await this.Context.Database.ExecuteSqlRawAsync(query);
Run Code Online (Sandbox Code Playgroud)

如果我直接对 SQL Server 数据库运行相同的原始 SQL 语句,它就可以正常工作。

扩展中是否有一些限制,RawSql实体中的字符串字段不能有 jsonstring?

有关如何使用容纳 jsonstring 的字符串实体字段之一运行原始查询的任何帮助吗?

Iva*_*oev 10

该问题是由SQL 字符串中的'{'和符号引起的,因为它们用于指定参数占位符,因此该字符串应该是函数的有效输入。事实上,EF Core 实现在某个时刻使用(即使您不传递参数),这又会生成相关异常。如果你这样做就可以看到'}'ExecuteSqlRaw{Async}string.Formatstring.Format

string.Format(query);
Run Code Online (Sandbox Code Playgroud)

'{'解决方案是通过在内部加倍和符号使其成为有效的格式字符串'}'。例如,在您的示例中:

string query = "update mytable set column1 = 100, column2= '[{{\"property1\":\"value1\",\"property2\":null}}]' where condition;update mytable set column1= 200, column2= '[{{\"property1\":\"value2\",\"property\":null}}]' where condition;"
Run Code Online (Sandbox Code Playgroud)

如果您尝试实际参数化您的 SQL,那就太好了。