Skip to content

Raw SQL parameter analyzer #1107

@jeremycook

Description

@jeremycook

This is a pretty subtle detail if you are not paying attention and do not already understand how FormattableStrings become strings unless you are explicit about maintaining the FormattableString type. It seems like providing an example of correct usage or elaborating on incorrect usage would help, as could linking to related documentation.

For example:
// UNSAFE: In this case sql is implicitly cast to a plain old string and which results in FormSql not being able to parameterize minAge.
var sql = $"SELECT * FROM People WHERE Age > {minAge}";
var query = context.People.FromSql(sql);

// SAFE: By explicitly declaring that sql as a FormattableString, FromSql will be able to parameterize minAge.
FormattableString sql = $"SELECT * FROM People WHERE Age > {minAge}";
var query = context.People.FromSql(sql);

Even more subtle is a formattable string that is composed of formattable strings may not result in parameterization like one might assume. Frankly it would be nice to enable throwing instead of only logging on potentially unsafe queries, but that's an issue for another day.

Related documentation: https://docs.microsoft.com/en-us/ef/core/querying/raw-sql#passing-parameters


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions