将参数传递给 .fromsql

3

我无法解决这个问题,感到很沮丧。我想在数据库中对一个人进行基本搜索,以下内容已经正常工作:

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

但是由于可能存在SQL注入的风险,这种方法并不好。因此,我尝试了另一种方法(因为我之前使用过它来调用存储过程,效果很好)。

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

这不起作用。我试过使用 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);

这也不起作用。

请问有人能告诉我哪里出了问题吗? 谢谢。


我看到你已经为表格类进行了类型化...为什么你没有使用Linq逻辑呢? - Marco Dal Zovo
IQueryable<VwSomeView> dbresult = db.vwSomeView.FromSql("select * from vwSomeView where firstname like '%{search}%' or lastname like '%{search}%'",para); . . . 尝试一下,可能会有用。@Morty - Waleed Naveed
@MarcoDalZovo 因为我还没有经常使用Linq,所以这完全没有想到。 - Morty
2个回答

3
使用 @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);

今天互联网信号不太好,所以我在发完我的回答后没有收到你的答复。谢谢。 - Morty

3

当然,在发布问题后仅10分钟我就找到了答案。

这是有效的。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接