Click here to Skip to main content
12,898,663 members (57,109 online)
Rate this:
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);

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
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
    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

I've not played with LINQ to SQL, but I imagine it's very similar to LINQ to Entities.
Marcus Kramer 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
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170424.1 | Last Updated 28 Sep 2012
Copyright © CodeProject, 1999-2017
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