mrJack
mrJack

Reputation: 1011

dynamic field with linqToEntity (c#)

my code :

        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();

        }

error :

The query syntax is not valid. Near term '@p0', line 6, column 7.

Upvotes: 0

Views: 137

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

Fields must be static. You cannot use wild cards in a field name. This Where extensions only builds Entity SQL query internally. Entity SQL follows the same rules as common SQL.

Edit:

Correct code is:

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();
    }
}

You must pass whole field's name and you must validate it - Entity SQL injections exists as well.

Upvotes: 1

Related Questions