1

If I have an Entity Framework expression stored as a string, like this:

var exp = "from user in users where user.Id == 1 select user.Name";

Is there a way to convert this to SQL using EF Core?

I don't need to run the SQL, just get the SQL that would be generated.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Slicc
  • 3,217
  • 7
  • 35
  • 70

2 Answers2

5

Yes, it's possible to run linq expression stored in string variable. For that purposes you need to import Microsoft.CodeAnalysis.CSharp.Scripting.

Here the snippet you can run with

using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;

var users = new List<User>() { new User { Id = 1, Name = "John" }, new User { Id = 2, Name = "Jane" } };
var exp = "from user in users where user.Id == 1 select user.Name";

ScriptOptions options = ScriptOptions.Default.AddReferences(typeof(User).Assembly);
options = options.AddImports("System.Linq");

var filteredUsers = await CSharpScript.EvaluateAsync<IEnumerable<string>>(exp, options, new Globals{ users = users });

public class User
{
    public int Id { get; set; }
    public string? Name { get; set; }
}

public class Globals
{
    public List<User> users;
}

So if you can execute an expression, you also can compile it to sql query. Hopefully ToQueryString() link1 link2 inside the string expression can help you to get the sql string

Hope it helps

Mustafa Özçetin
  • 1,893
  • 1
  • 14
  • 16
Adalyat Nazirov
  • 1,611
  • 2
  • 14
  • 28
  • Hello, thanks for the suggestion. In this instance I don't actually want to run the expression, instead i want to convert the expression to a SQL query. – Slicc Jun 16 '23 at 06:19
  • 1
    just edited the answer. I get you. So you can add more references in the sample above and run `ToQueryString()` instead of just returning result – Adalyat Nazirov Jun 16 '23 at 06:23
1

It is not recommended as sql injection can done through this technique. imagine ur storing sql query like drop table tablename it will drop ur data.

  • As i mentioned, i won't be running the sql, i just want the converted sql as a string. – Slicc Jun 16 '23 at 06:11
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 16 '23 at 12:18