2012-06-21 18 views
0

我不知道是否有人能向我解释在运行时检索LINQ表达式身体的ToString

(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); 
+0

没有执行得相当好肯定不能是检索字符串和操作字符串的缺点。当你试图将结果*字符串作为结构化数据处理时,潜在的不利之处就在于此。当你解析它时,你将如何处理你无法用'Expression'本身来做的结果? – AakashM

+0

(templates.usable == True)AndAlso(templates.name ==“tc1”)非常类似于(templates.usable = True)和(templates.name =“tc1”),它可以用作where语句一个选择语句。在(templates => templates.usable == true && templates.id == templateId)的情况下,它应该是(templates => templates.usable == true && templates.id == id),它与(模板.usable = true AND templates.id = @id) 模板也是要查询的表的名称。所以我的想法是“交换”== for =,也是等等 –

+0

我的观点是,无论您要从其*文本表示*中提取的信息是否已经存在于“Expression”本身中,所以您会更好关闭询问*,而不是必须解析文本。我没有看过整个表达式访问者的东西(在待办事项列表中!),但是当你为表达式树和表达式访问者的谷歌时,有资源[任意例子](http://www.aboutmycode.com/net -ifwork/building-expression-evaluator-with-expression-trees-in-csharp-part-1 /) – AakashM

回答

1

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

所创建的参数是从小巧精致的DynamicParameters,但很容易被交换为标准的SQL参数

没有做过很多测试,但还没有出现查询在此阶段