[英]Store Jsonstring using Entity Framework Core ExecuteSqlRawAsync
I have an entity in which for one of the string field I want to store jsonstring (json equivalent of List of MyObject) using EF Core ExecuteSqlRawAsync
extension.我有一个实体,其中一个字符串字段我想使用 EF Core ExecuteSqlRawAsync
扩展存储 jsonstring(与 MyObject 列表等效的 json)。
However, I am getting this error:但是,我收到此错误:
Input string was not in a correct format.输入字符串的格式不正确。
from EF at来自英孚
Microsoft.EntityFrameworkCore.Storage.Internal.RawSqlCommandBuilder.Build. Microsoft.EntityFrameworkCore.Storage.Internal.RawSqlCommandBuilder.Build。
I am using EF Core version 3.1.我正在使用 EF Core 3.1 版。
Please find below an overview of sample similar to what I am trying:请在下面找到类似于我正在尝试的示例概述:
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);
If I run the same raw SQL statement directly against the SQL Server database, it works just fine.如果我直接针对 SQL 服务器数据库运行相同的原始 SQL 语句,它就可以正常工作。
Is there some limitation in the RawSql
extension that string field in an entity cannot have jsonstring? RawSql
扩展中是否存在实体中的字符串字段不能有 jsonstring 的限制?
Any help how to run raw query with one of the string entity field accommodating jsonstring?任何帮助如何使用包含 jsonstring 的字符串实体字段之一运行原始查询?
The problem is caused by the '{'
and '}'
symbols inside SQL string, because in ExecuteSqlRaw{Async}
they are used to specify parameter placeholders, so the string should be a valid input for string.Format
function.问题是由 SQL 字符串中的'{'
和'}'
符号引起的,因为在ExecuteSqlRaw{Async}
中它们用于指定参数占位符,因此字符串应该是string.Format
function 的有效输入。 In fact EF Core implementation uses string.Format
(even though you don't pass parameters) at some point, which in turn generates the exception in question.事实上,EF Core 实现在某些时候使用string.Format
(即使您不传递参数),这反过来又会产生有问题的异常。 Which can be seen if you do如果你这样做可以看到
string.Format(query);
The solution is to make it valid format string by doubling '{'
and '}'
symbols inside.解决方案是通过在内部加倍'{'
和'}'
符号使其成为有效的格式字符串。 For instance, in your sample:例如,在您的示例中:
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;"
Also it would be good if you try actually parameterizing your SQL.如果您尝试实际参数化您的 SQL,那也会很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.