Robert
Robert

Reputation: 1794

Pass field name in dapper query

I'm creating a function where I check if a maintenance day is checked in the database. Each Column is Maintenance + DayName (MaintenanceSunday, MaintenanceMonday, etc.).

It appears that anytime you pass in an object, it wants to take the value of what is being checked and not "inject" the string. Is there a way to safely achieve this (ie not String.Format("where {0} = ...", field))? I really don't want to open up the possibility of SQL Injection here (though there is an earlier check to see if q.ToUpper() is in a list of "SUNDAY", "MONDAY", etc. so I guess there's that safeguard)

I attempted this, but it bombs attempting to compare 'Maintenancesunday' to true (bit):

string field = "Maintenance" + q; // q = "sunday"
return conn.Query<Data>("SELECT * FROM Data WHERE @Field = @Value", new { Field = field, Value = true }).ToList();

Upvotes: 2

Views: 1837

Answers (1)

Henk Mollema
Henk Mollema

Reputation: 46591

Dapper just uses ADO.NET, which doesn't support parameterized column names. I guess you need some hard-coding to accomplish this.

Upvotes: 3

Related Questions