使用LINQ进行动态查询将不起作用

Nik*_*las 1 linq asp.net-mvc dynamic

我尝试了几种方法来执行一个简单的查询,但没有成功.

var result = db.Persons.Where("surname = bob");  
Run Code Online (Sandbox Code Playgroud)

以上将给出错误:'Person'类型中不存在属性或字段'bob'

var result = db.Persons.Where("surname = 'bob'");  
Run Code Online (Sandbox Code Playgroud)

以上将给出错误:字符文字必须包含一个字符

有没有其他人有这些问题,你做了什么?
是不是动态LINQ假设像这样工作或有旧版本或什么?

我已将Dynamic.cs我的项目添加到了我的项目中using System.Linq.Dynamic.

Dar*_*rov 9

在进行比较时,您需要两个==,并且为了避免注入,请使用以下重载:

var result = db.Persons.Where("surname == @0", "bob");
Run Code Online (Sandbox Code Playgroud)

另外,我建议您下载并查看您使用的产品随附的示例.Scott Gu也在博客上写过这篇文章.


Sim*_*all 5

var result = db.Persons.Where("surname == \"bob\"");
Run Code Online (Sandbox Code Playgroud)

会起作用,但你应该确保鲍勃真正是什么也被正确转义。

也就是说,你最好有这样的东西:

String bob = "bob"; // or whatever
var result = from p in db.Persons p
             where p.surname = bob
             select p 
Run Code Online (Sandbox Code Playgroud)

  • 这听起来像是在乞求注射攻击……要非常小心! (3认同)