带有Like子句的EF核心原始查询

问题描述 投票:0回答:1

我想使用允许我使用Like子句的EF FromSqlInterpolated或FromSqlRaw创建查询,但是我不知道在不向SqlInjection攻击打开应用程序的情况下正确的方法是什么。第一种方法将我带到以下代码

var results = _context.Categories.FromSqlInterpolated(
$"Select * from Category where name like {"%" + partialName + "%"}");

[第一个测试工作正常,当提供期望的字符串时它返回结果,而当我提供诸如';select * from Category Where name='Notes'--%';之类的东西时不返回任何结果我仍然对SqlInjection不太了解,至少不足以使之前显示的查询感到安全。有人知道查询是否安全或是否有正确的方法吗?谢谢

entity-framework .net-core sql-injection
1个回答
1
投票
来自this document

FromSqlInterpolated和ExecuteSqlInterpolated方法允许使用字符串插值语法,其方式为防止SQL注入攻击。

var results = _context.Categories.FromSqlInterpolated( $"Select * from Category where name like {"%" + partialName + "%"}");
或者您也可以通过这种方式将查询更改为Linq-to-Entity

var results = _context.Categories.Where(p => p.name.Contains(partialName ));

© www.soinside.com 2019 - 2024. All rights reserved.