简体   繁体   English

将参数传递给.fromsql

[英]Passing parameter to .fromsql

I can not get this problem figured out and I am getting frustrated. 我无法弄清楚这个问题,我感到沮丧。 I want to do a basic search for a person in the database and the following is working fine 我想对数据库中的人进行基本搜索,以下工作正常

 IQueryable<VwSomeView> dbresult = db.vwSomeView.FromSql("select * from vwSomeView where firstname like '%" + searchfor + "%' or lastname like '%" + searchfor + "%'");

but it is bad because of possible SQL injections. 但这很糟糕,因为可能会进行SQL注入。 So I tried this (because I used it befor to call a stored procedure and it is working fine) 因此,我尝试了此操作(因为我在调用存储过程之前就使用了它,并且工作正常)

IQueryable<VwSomeView> dbresult = db.vwSomeView.FromSql("select * from vwSomeView where firstname like '%{0]%' or lastname like '%{0}%'",searchfor);

wich isn't working. 不能正常工作。 I tried it with SqlParameter 我尝试了SqlParameter

SqlParameter para = new SqlParameter("search", searchfor);
IQueryable<VwSomeView> dbresult = db.vwSomeView.FromSql("select * from vwSomeView where firstname like '%@search%' or lastname like '%@search%'",para);

that's not working either. 这也不起作用。

Could someone please tell me what I am doing wrong? 有人可以告诉我我做错了吗? Thanks 谢谢

Use @search as a variable in SQL (and not within a string) and it should work. 使用@search作为SQL中的变量(而不是在字符串中),它应该可以工作。

SqlParameter para = new SqlParameter("search", "%" + searchfor + "%");
IQueryable<VwSomeView> dbresult = db.vwSomeView.FromSql("select * from vwSomeView where firstname like @search or lastname like @search",para);

Well of course I figured it out only 10min after posting the question. 当然,我在发布问题后仅10分钟就发现了问题。 This is working 这工作

DbParameter para = new SqlParameter("search", "%"+searchfor+"%");
IQueryable<VwSomeView> dbresult = db.vwSomeView.FromSql($"select * from vwSomeView where firstname like @search or lastname like @search",para);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM