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
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With