Search code examples
c#sqllinqquotes

auto SQL field's quotation marks by type in c#


Suppose that I want to create an SQL SELECT statement dynamically with reflection on primary key. I search in the table for primary keys and then, I make the statement.

Problem is, I don't know the type of fields that compose the primary key before getting them. So, if it's a string or date, I must add quotation marks but not if it's an int.

Atm, I am doing like that :

var type = field.GetType().Name;
if (type.ToLower().StartsWith("string") || type.ToLower().StartsWith("date"))
{
    field = "\"" + field + "\"";
} else if (type.ToLower().StartsWith("char"))
{
    field = "\'" + field + "\'";
}

With this code, I can handle some SQL types but there are a lot more.

My problem is that it's combined with LinQ. I got a DataContext object and a generic type table from the context. And context.ExecuteQuery only allows parameters to be passed has values. I also tried with Dynamic LinQ but I got the same problem

Does anyone know a better solution?


Solution

  • That is simply the wrong way to write SQL. Parameterize it and all these problems evaporate (as do problems with "which date format to use", etc. And of course the biggie: SQL injection.

    Then it just becomes a case of adding @whatever into the TSQL, and using cmd.Parameters.AddWithValue("whatever", field) (or similar).


    Update (from comments): since you mention you are using DataContext.ExecuteQuery, this becomes easier: that method is fully parameterized using the string.Format convention, i.e.

    object field = ...;
    var obj = db.ExecuteQuery<SomeType>(
          "select * from SomeTable where Id = {0}", field).ToList(); // or Single etc
    

    No string conversions necessary.

    (the last parameter is a params object[], so you can either pass multiple discreet terms, or you can populate an object[] and pass that, if the number of terms is not fixed at compile-time; each term in the array maps by (zero-based) index to the {0}, {1}, {2}... etc token in the query)