使用 Entity Framework Core ExecuteSqlRawAsync 存储 Jsonstring

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

我有一个实体,对于其中一个字符串字段,我想使用 EF Core

ExecuteSqlRawAsync
扩展来存储 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);

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

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

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

c# .net-core entity-framework-core
2个回答
12
投票

问题是由 SQL 字符串中的

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

string.Format(query);

解决方案是通过在内部加倍

'{'
'}'
符号使其成为有效的格式字符串。例如,在您的示例中:

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;"

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


0
投票

解决这个问题最好的办法就是使用SqlParameter

object[] sqlParams = new object[] {new SqlParameter("@column2"," [{"property1":"value1","property2":null}]") };

字符串查询=“更新mytable设置column1 = 100,column2=@column2

等待 this.Context.Database.ExecuteSqlRawAsync(query,sqlParams);

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