我正在尝试在 MVC 项目中过滤带有两个下拉列表的模型
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:字符文字必须只包含一个字符
我明白了 += " 和 CODICE_CLIENTE = '" + 搜索。客户端 + "'";
我看到最后的顶点是'"
如何解决
此示例转换为 Linq 而不允许 SQL 注入攻击
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 + "'";
}
}
看起来像:
IQueryable<x> query = (from x in db.TABLE....
join y in db.TABLE...);
if (search.anno != null)
{
query = query.Where(x => x.ANNO == search.anno);
}
if (search.Cliente != null)
{
query = query.WHere(x => x.CODICE_CLIENTE == search.Cliente);
}
var model = query.ToList(); // or await query.ToListAsync();
我解决了...
字符串,其中 = 字符串。空; 对象 [] 参数 = 空;
if (search.anno != null)
where = " ANNO = @0 ";
parameters = new object[] { search.anno };
if (search.Cliente != null)
{
if (!string.IsNullOrEmpty(where))
{
where += " && CODICE_CLIENTE = @1";
parameters = new object[] { search.anno, search.Cliente };
}
else
{
where = " CODICE_CLIENTE = @0";
parameters = new object[] { search.Cliente };
}
}
if (search.linea != null)
{
if (!string.IsNullOrEmpty(where))
{
where += " && LINEA.Contains(@2) ";
parameters = new object[] { search.anno, search.Cliente, search.linea };
}
else
{
where = " LINEA.Contains(@0) ";
parameters = new object[] { search.linea };
}
}
但问题出在 LINEA 属性(匿名类型(:它是字符串,我不能再次使用 Contains(@p( 坦克进行所有重播并帮助您提供
表达式使用双等号,对字符串使用双引号 字符串,其中 = 字符串。空;
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注入,应该避免,您应该使用参数,如下所示:
var model = (from x in db.TABLE.... join y in db.TABLE...).Where(whereString, params)...