Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. So I tried this (because I used it before 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);

which isn't working. I tried it with 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

like image 333
Morty Avatar asked Aug 30 '26 06:08

Morty


2 Answers

Use @search as a variable in SQL (and not within a string) and it should work.

SqlParameter para = new SqlParameter("search", "%" + searchfor + "%");
IQueryable<VwSomeView> dbresult = db.vwSomeView.FromSql("select * from vwSomeView where firstname like @search or lastname like @search",para);
like image 85
Noren Avatar answered Aug 31 '26 20:08

Noren


Well of course I figured it out only 10min after posting the question. 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);
like image 34
Morty Avatar answered Aug 31 '26 19:08

Morty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!