是否可以将参数化的SQL查询转换为LinQ to SQL? [英] Is it possible to transform a parameterized SQL query into LinQ to SQL?
问题描述
大家好,
是否可以将带有参数的查询转换为LinQ to SQL(保持参数不变)?
这是我到目前为止在普通SQL中所拥有的.
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();
我想将其转换为等效的LinQ to SQL语法,并尽可能保持参数不变.我主要担心的是,如果可能的话,我想防止SQL注入.
这段代码现在可以正常工作.
谢谢大家!
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!
推荐答案
使用LINQ to Entities,它看起来像这样(context
变量是您的实体模型的实例):
With LINQ to Entities, it''d look like this (thecontext
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();
我没有玩过LINQ to SQL,但我想它与LINQ to Entities非常相似.
I''ve not played with LINQ to SQL, but I imagine it''s very similar to LINQ to Entities.
这篇关于是否可以将参数化的SQL查询转换为LinQ to SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!