Linq dynamic having issue with double quote

强颜欢笑 提交于 2021-01-29 18:39:25

问题


I am using System.Linq.Dynamic; to generate dynamic linq query which featch records from db context.

I generate where clause in string format for dynamic linq, It works perfectly if input does not have any double quote. However, it throws error once input string contains double quote.

I followed Stack Overflow existing solution dynamiclinq-escaping-double-quotes-inside-strings but it does not helped because I wanted to use LIKE operator.

I'm using Contains condition in my where clause because I need LIKE operator for query. Please follow below sample code...

//name should contains  "6"" WHITE COLOR

var whereClause = "(!flag.Contains(\"D\")) AND (Name.Contains(\"\"6\"\" WHITE COLOR\"\"))";

var result = context.Product.Where(whereClause).ToList();

Once I execute above query it throws error as ')' or operator expected. But as per above where clause it looks all bracket are fine not sure is it any issue with dynamic query dll.

Thank you for any advice.


回答1:


You need to escape the escape symbol \.

//name should contains  "6"" WHITE COLOR

var whereClause = "(!flag.Contains(\"D\")) AND (Name.Contains(\"\\\"6\\\"\\\" WHITE COLOR\"))";

var result = context.Product.Where(whereClause).ToList();

Or use parameterization.

//name should contains  "6"" WHITE COLOR

var flag = "\"D\"";
var name = "\"6\"\" WHITE COLOR";
var whereClause = "(!flag.Contains(@0)) AND (Name.Contains(@1))";

var result = context.Product.Where(whereClause, @0, @1).ToList();


来源:https://stackoverflow.com/questions/58082268/linq-dynamic-having-issue-with-double-quote

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!