Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: SQL LINQ Parameter
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:26am

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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  
v2
Comments
Marcus Kramer at 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)

  Print Answers RSS
0 OriginalGriff 490
1 Gihan Liyanage 338
2 ChauhanAjay 180
3 Vinay Mistry 160
4 Sergey Alexandrovich Kryukov 153
0 Sergey Alexandrovich Kryukov 9,011
1 OriginalGriff 7,941
2 CPallini 2,603
3 Richard MacCutchan 2,121
4 Abhinav S 1,928


Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 28 Sep 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100