Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone,

Is it possible to transform a query with parameters into LinQ to SQL (keeping the parameters in tact)?

This is what I have so far in plain SQL.

SQL
SqlCeCommand trans_comm = new SqlCeCommand("SELECT DISTINCT transmission_type FROM vehicles WHERE make = @make AND model_name = @model AND model_year = @model_year AND engine_type = @engine_type", conn);

            trans_comm.CommandType = CommandType.Text;
            trans_comm.Parameters.AddWithValue("@make", makeComboBox.SelectedItem);
            trans_comm.Parameters.AddWithValue("@model", modelComboBox.SelectedItem);
            trans_comm.Parameters.AddWithValue("@model_year", yearComboBox.SelectedItem);
            trans_comm.Parameters.AddWithValue("@engine_type", engineComboBox.SelectedItem);
            trans_comm.ExecuteNonQuery();


I want to transform this to the equivalent LinQ to SQL syntax, keeping parameters in tact, if possible. My main concern is that I want to prevent SQL injection, if possible.

This code works fine as is, right now.

Thanks everyone!
Posted

1 solution

With LINQ to Entities, it'd look like this (the context variable would be an instance of your entity model):
C#
var cars = (
  from car in context.vehicles
  where
    car.make == makeComboBox.SelectedItem &&
    car.model == modelComboBox.SelectedItem &&
    car.model_year == yearComboBox.SelectedItem &&
    car.engine_type == engineComboBox.SelectedItem
  select new
  {
    transmission_type = car.transmission_type
  }).Distinct().ToList();

I've not played with LINQ to SQL, but I imagine it's very similar to LINQ to Entities.
 
Share this answer
 
v2
Comments
fjdiewornncalwe 28-Sep-12 20:50pm    
+5. Perfect.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900