我想我在这件事上走对了路,但遇到一些我会诚实的事情是在阻挠我。
我有一个带有地理的表,所以现在,直到Geo支持出现在EFCore之前,我正在为特定的表构建自己的SQL查询。它实际上是一个搜索,因此它基于一组可以传递到某个端点的查询参数动态构建。
因此,我使用反射在DTO上迭代,并根据哪些属性具有值来构建SQL查询。我将从我的查询生成器返回一个元组,其中包含一个List<SqlParameter>和List<string>,后者是原始的sql,前者是params。
然后,我做了一个集合,把所有这些放在一起。
我得到以下问题:
//This is inside my SQL Param builder method which returns a
//Tuple of sqlQuery and sqlParams
if (!string.IsNullOrEmpty(search.Municipality))
{
sqlQuery.Add("Municipality LIKE %@Municipality%");
sqlParams.Add(new SqlParameter("@Municipality", search.Municipality));
}
//Thi lines aggregates the result to build a SELECT * FROM query
sql = sqlParams.Item2.Aggregate(sql, (current, t) => current + " AND " + t);
//This executes the query
return DbSet.FromSql(sql, sqlParams.Item1.ToArray()).ToListAsync();
//This is the generated SQL string that is printed from the sql variable above
SELECT * FROM AirportData WHERE Municipality LIKE %@Municipality%
//This is the error I get from EFCore
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '@Municipality'.我现在只是用一个param来完成这个任务。
对于为什么不将SQL Param转换为查询的值,有什么想法吗?我是不是完全离校了?谢谢您的期待和建议?
发布于 2018-09-14 07:51:41
错误不是来自error,而是来自SqlServer,因为%@Municipality%不是一个有效的SQL表达式。
它应该类似于'%' + @Municipality + '%'或N'%' + @Municipality + N'%',因此相应地修改should。
sqlQuery.Add("Municipality LIKE '%' + @Municipality+ '%'");发布于 2018-09-14 08:03:04
我猜EF核心不支持直接的so参数,所以我使用了这个示例。FromSql(string,params object[])字符串: sql : sql参数(@key或{0})
SqlCommand command = new SqlCommand
{
CommandText = @"SELECT DISTINCT * FROM F_SearchQuery(@keys)"
};
SqlParameter k = new SqlParameter("@keys", keys ?? (object)DBNull.Value);
return _repositoryCustom.JobSearchQuering.FromSql(command.CommandText, k).ToList();https://stackoverflow.com/questions/52327092
复制相似问题