Click here to Skip to main content
Sign Up to vote bad
good
See more: SQLLINQParameter
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.
 
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 28 Sep '12 - 11:26


1 solution

With LINQ to Entities, it'd look like this (the context variable would be an instance of your entity model):
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.
  Permalink  
Comments
Marcus Kramer - 28 Sep '12 - 20:50
+5. Perfect.

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 523
1 Mahesh Bailwal 393
2 Maciej Los 205
3 Aarti Meswania 200
4 Tadit Dash 145
0 Sergey Alexandrovich Kryukov 9,607
1 OriginalGriff 7,214
2 CPallini 3,943
3 Rohan Leuva 3,261
4 Maciej Los 2,758


Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 28 Sep 2012
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid