efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Provide better error message when SQL query strings fail in string formatting

Open milenstack opened this issue 9 years ago • 5 comments

var sql=“insert into talele(data)value(‘{data:123}’);”; this.Database.ExecuteSqlCommand(sql);

System.FormatException: Input string was not in a correct format. at System.Text.StringBuilder.FormatError() at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args) at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args) at System.String.Format(String format, Object[] args) at Microsoft.EntityFrameworkCore.Storage.Internal.RawSqlCommandBuilder.Build(String sql, IReadOnlyList`1 parameters) at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlCommand(DatabaseFacade databaseFacade, String sql, Object[] parameters)

milenstack avatar Jun 12 '17 09:06 milenstack

Looks like this line needs to check that substitutions.Count > 0, perhaps? https://github.com/aspnet/EntityFramework/blob/f386095005e46ea3aa4d677e4439cdac113dbfb1/src/EFCore.Relational/Storage/Internal/RawSqlCommandBuilder.cs#L76

ErikEJ avatar Jun 12 '17 14:06 ErikEJ

this is bug

milenstack avatar Jun 12 '17 14:06 milenstack

@gujunxiong The curly braces are interpreted as place markers for query parameters. If you want to include curly braces without them being interpreted in this way, then you'll need to escape them--something like this:

var sql=“insert into talele(data)value(‘{{data:123}}’);”;
this.Database.ExecuteSqlCommand(sql);

Leaving this issue open since we should wrap the FormatException and provide some guidance on this.

ajcvickers avatar Jun 12 '17 19:06 ajcvickers

The same problem if I have curly braces in the comment message into my SQL script.

-- some comment message {GUID}
select newId();

AleXKarasev avatar Jan 03 '19 12:01 AleXKarasev

I had the same Issue as AleX, due to the unhelpful error message, it took me hours to diagnose the issue. I was effectively manually doing JSON munging due to SQL2012 not supporting JSON_VALUE. This meant the SQL Query I was running had single and double quotes etc all through it which I had escaped correctly but it was still failing. The really confusing part was when debugging, looking at the actual string that was being passed into ExecuteSqlRaw executed as expected in SSMS. It was only after hours of trial and error that I found the composite formatting documentation which said that braces also needed to be escaped.

thedarkfalcon avatar Jun 10 '24 23:06 thedarkfalcon