英文:
Can I use Entity Framework Core to generate SQL from an expression stored as a string?
问题
如果我有一个存储为字符串的 Entity Framework 表达式,类似于这样:
var exp = "from user in users where user.Id == 1 select user.Name";
是否有一种方法可以使用 EF Core 将其转换为 SQL?
我不需要运行 SQL,只需要获取将生成的 SQL。
英文:
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.
答案1
得分: 5
是的,可以运行存储在string
变量中的linq表达式。为此,您需要导入Microsoft.CodeAnalysis.CSharp.Scripting
。
以下是您可以运行的代码段:
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;
}
因此,如果您可以执行一个表达式,您也可以将其编译成SQL查询。希望ToQueryString()
link1 link2 中的字符串表达式可以帮助您获取SQL字符串。
希望这有所帮助。
英文:
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
答案2
得分: 1
不建议使用这种技术,因为可以通过这种技术进行SQL注入攻击。想象一下,如果您存储了类似于"drop table tablename"的SQL查询,它将删除您的数据。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论