最近再做一个项目,出现一个小bug,bug虽小,但是却要命啊。下面我show下我解决问题的方法。
View层代码:
@model List<mhq.Blog.Model.Blog><blockquote class="layui-elem-quote">文章管理</blockquote> <div style="padding:10px;"><div><a class="layui-btn" href="~/Admin/Blog/Add"><i class="layui-icon"></i> 添加</a></div><table class="layui-table"><thead><tr><th>发布时间</th><th>boke标题</th><th>所属分类</th><th>访问量</th><th>排序号</th><th>管理</th></tr></thead><tbody>@foreach (var blog in Model){<tr><td>@blog.createdate.ToString("yyyy-MM-dd HH:mm")</td><td>@blog.title</td><td>@blog.caname</td><td>@blog.visitnum</td><td>@blog.sort</td><td><a style="margin-right:20px" href="~/Admin/Blog/Add/@blog.id"><i class="layui-icon"></i>编辑</a><a href="javascript:void()0;" οnclick="del(@blog.id)"><i class="layui-icon"></i>删除</a></td></tr>}</tbody></table> </div><script>/* 删除*/function del(id) {layui.use('layer', function () {var layer = layui.layer;var $ = layui.jquery;layer.confirm("是否确认删除?", function () { var url = "/Admin/Blog/Del/" + id;$.post(url, function (data) {layer.alert(data, function () { location.reload(); });})})})}</script>
Controller层代码:
public IActionResult Index(){List<Model.Blog> list = dal.GetList(" 1=1 order by sort asc,id desc");return View(list);}
Dal层代码:
/// <summary>/// 查询/// </summary>/// <param name="cond">查询条件</param>/// <returns></returns>public List<Model.Blog> GetList(string cond){// Dapper – Simple Listusing (var connection = ConnectionFactory.GetOpenConnection()){string sql = "select * from blog ";if (!string.IsNullOrEmpty(cond)){sql=sql+$" where{cond}";}var list = connection.Query<Model.Blog>(sql).ToList();return list;}}
我这里出现的错误是“System.Data.SqlClient.SqlException:““=”附近有语法错误。”如图:
解决方法:
1、首先在此处方法上添加断点,如图:
2、运行程序到此断点(F5运行程序)
3、单步运行(F11)
对sql、 list添加监视,我们可以清楚的看到list里面的查询语句为:
select * from blogwhere1=1 order by sort asc,id desc
显然这是错误的查询语句。
如图:
正确的应为:
select * from blog where 1=1 order by sort asc,id desc
也就是说blog与where之间和where与1=1之间缺少空格。
所以我们只要在相关的代码中加上空格就OK了。