linqToEntity的动态字段(c#)

时间:2011-08-24 20:07:08

标签: c#-4.0 entity-framework-4 linq-to-entities

我的代码:

        public List<tblBook> GetBook(string NameField, string Value)
        {
            return (this.Entities.Book.Where(
            "it.@p0 NOT LIKE @p1",

new ObjectParameter("p0", string.Format("%{0}%", NameField)),

new ObjectParameter("p1", string.Format("%{0}%", Value)))).ToList();

        }

错误:

  

查询语法无效。近期'@ p0',第6行,第7栏。

1 个答案:

答案 0 :(得分:1)

字段必须是静态的。您不能在字段名称中使用通配符。此Where扩展仅在内部构建实体SQL查询。实体SQL遵循与常见SQL相同的规则。

编辑:

正确的代码是:

public List<tblBook> GetBook(string NameField, string Value)
{
    return this.Entities.Book.Where(
               String.Format("it.{0} NOT LIKE @p0", NameField),
               new ObjectParameter("p0", string.Format("%{0}%", Value))).ToList();
    }
}

您必须传递整个字段的名称,并且必须验证它 - 实体SQL注入也存在。