LINQ MVC中的动态位置 [英] Dynamic Where in linq MVC

查看:95
本文介绍了LINQ MVC中的动态位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在MVC项目中过滤带有两个下拉菜单的模型

I am trying to filter a model with two dropdown in an MVC project

var model = (from x in db.TABLE....
            join y in db.TABLE...).Where(where)...

我的逻辑是

            String where = string.Empty;

            if (search.anno != null)
                where = " ANNO = " + search.anno ;

            if (search.Cliente != null)
            {
                if (!string.IsNullOrEmpty(where))
                {
                    where += " And CODICE_CLIENTE = '" + search.Cliente + "'";                 }
                else
                {
                    where = " CODICE_CLIENTE = '" + search.Cliente + "'";
                }
            }

我得到一个错误:System.Linq.Dynamic.ParseException:字符文字必须恰好包含一个字符

i get an error: System.Linq.Dynamic.ParseException: Character literal must contain exactly one character

我在+ ="And CODICE_CLIENTE ='" + search.Cliente +'";

i get that in where += " And CODICE_CLIENTE = '" + search.Cliente + "'";

我看到末尾的Apex是'"

i saw that the Apex at the end is '"

如何解决

推荐答案

您需要对表达式使用双等于和对字符串使用双引号 字符串,其中= string.Empty;

You need to use double equals for the expression and double quotes for the strings String where = string.Empty;

            if (search.anno != null)
                where = " ANNO == " + search.anno ;

            if (search.Cliente != null)
            {
                if (!string.IsNullOrEmpty(where))
                {
                    where += " And CODICE_CLIENTE == \"" + search.Cliente + "\"";                 }
                else
                {
                    where = " CODICE_CLIENTE == \"" + search.Cliente + "\"";
                }
            }

注意,这很容易发生SQL注入,应避免使用,应该使用类似以下的参数:

Note that this is prone to SQL injection and should be avoided, you should use parameters, something like this:

var model = (from x in db.TABLE.... join y in db.TABLE...).Where(whereString, params)...

这篇关于LINQ MVC中的动态位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆