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