【问题标题】:LINQ Expressions Body ToStringLINQ 表达式正文 ToString
【发布时间】:2012-06-21 06:00:01
【问题描述】:

我想知道是否有人可以向我解释检索的缺点

(Expression<Func<T, bool>>) Expression.Body

在运行时并将其作为字符串操作?

例如给出以下内容

public partial class Tests : Form
{
    public Tests()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        TestClass t = new TestClass();
        textBox1.Text = t.Evaluate(templates => templates.usable == true && templates.name == "tc1");
    }       
}

public class TestClass
{
    public string name { get; set; }
    public bool usable { get; set; }
}

public static class Helpers
{
    public static string Evaluate<T>(this T input,Expression<Func<T, bool>> Expression) where T : class
    {

        return Expression.Parameters.Single().Name + " " + Expression.Body;

    }
}

返回

templates ((templates.usable == True) AndAlso (templates.name == "tc1"))

我想知道检索这个然后通过正则表达式解析它可能会出现什么样的性能问题

回答为什么?我一直在玩 Dapper,但没有一个预先存在的扩展(我见过)吸引我

我希望能够以与 EF 类似的方式对其进行操作

_repo.Select(templates=>templates.usable== true && templates.id == templateId);

【问题讨论】:

  • 检索字符串和对字符串进行操作肯定不会有坏处。当您尝试将 resulting 字符串作为一段结构化数据处理时,潜在的缺点将是。当你解析它时,你将如何处理Expression 本身无法处理的结果?
  • (templates.usable == True) AndAlso (templates.name == "tc1") 非常类似于 (templates.usable = True) And (templates.name = "tc1") 可以用作 select 语句中的 where 语句。在 (templates=>templates.usable== true && templates.id == templateId) 的情况下,它应该是 (templates=>templates.usable== true && templates.id == id) 类似于 (templates .usable= true AND templates.id = @id) templates 也是要查询的表名。所以这个想法是“交换”== 为 =,以及等
  • 我的意思是,你要从它的文本表示中提取的任何信息都已经在Expression本身中,所以你最好询问 而不必解析文本。我自己还没有看过整个表达式访问者的东西(在待办事项列表上!)但是当你用谷歌搜索表达式树和表达式访问者时,周围有资源,arbitrary example
  • 谢谢——我没有的原因是我可能没有从我看到的例子中真正理解表达式树的本质——这个例子让我有了一个可以遵循的起点.

标签: regex string linq lambda


【解决方案1】:

感谢您推动使用实际表达式而不是解析文本。 对于任何感兴趣的人,我已经发布了我的 sqlexpression 项目初稿的链接。Google Code - SqlExpression.cs

创建的参数是来自 Dapper 的 DynamicParameters,但可以轻松交换为标准 sql 参数

尚未进行大量测试,但查询在现阶段似乎表现相当不错

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2019-09-18
    • 2023-04-02
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多