Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ef Core vs Linq on interpolated string

Using interpolated strings to send sql server queries, why with a datacontext on LINQ to SQL you need to add single quotes ?

db.ExecuteCommand($"delete table where date = '{date:yyyy-MM-dd}'");

while with EF Core you need to remove them ?

db.Database.ExecuteSqlCommand($"delete table where date = {date:yyyy-MM-dd}"); 

and why in EF Core, if you're using String.Format instead of interpolation, you need to put back the single quotes:

String.Format("delete table where date='{0}'", date.ToString("yyyy-MM-dd"));
like image 768
sofsntp Avatar asked Oct 16 '22 13:10

sofsntp


1 Answers

The main difference is that this: $"hello {variable}" is not a string. It's a FormattableString. And Entity Framework will take advantage of that and use it to parse parameters out of it.

String.Format on the other hand will create a new, formatted string without meta-information what was (or should be) formatted. There is no good way for entity framework to parse that into database parameters. It will have to send it to the database as is.

So to sum it up: If you pass a string, it has to have proper formating so the database will understand the text. If you pass entity framework something it understands and can parse the meta data out of, it will convert it to database parameters and you don't need proper formatting, because it will not be send as plain text, but as text with database parameters.

Why doesn't Linq-to-Sql use the power of FormattableString? Probably because it was deprecated before this feature even existed.

like image 50
nvoigt Avatar answered Oct 20 '22 11:10

nvoigt