I'm trying to create a dynamic WHERE clause with LINQ. I have a working example but I'm worried that it's not safe from SQL injection.
The following LINQ code:
var oQuery = _db.People.Where("FirstName.Contains(@0)", "kev");
produces the following SQL:
SELECT
[Extent1].[FirstName] AS [[FirstName],
[Extent1].[LastName] AS [[LastName],
WHERE [Extent1].[[FirstName] LIKE '%kev%'
This works great, but now I want to use a dynamic column name as well. So I was thinking I would do the following:
var oQuery = _db.People.Where("@0.Contains(@1)", strSelectedColumn,"kev");
But this produces the following SQL:
SELECT
[Extent1].[FirstName] AS [[FirstName],
[Extent1].[LastName] AS [[LastName],
WHERE N'FirstName' LIKE N'%kev%'}
which obviously is wrong and gives 0 rows as result because he is comparing 2 strings. By using the params LINQ will probably just inject the params as string when the query is build and not use the effective column name during the build.
The solution is to just use the following LINQ Query:
var oQuery = _db.People.Where(strSelectedColumn + ".Contains(@0)", "kev");
But this result in possible unsafe SQL which can be used to inject SQL.
How can I use my dynamic LINQ columns and still get safe code?