【EF框架】使用params参数传值防止SQL注入报错处理

通过SqlParameter传时间参数,代码如下:

                    var param = new List<SqlParameter>();
                    param.Add(new SqlParameter("@StartTime", DateTime.Parse(req.StartTime)));
                    param.Add(new SqlParameter("@EndTime", DateTime.Parse(req.EndTime)));
                    
                    response.List = _ctx.Database.SqlQuery<ReceiveSummeryItem>(sql, param.ToList()).ToList();

结果一直报错

不存在从对象类型 System.Collections.Generic.List`1[[System.Data.SqlClient.SqlParameter, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] 到已知的托管提供程序本机类型的映射。

英文报错

No mapping exists from object type System.Collections.Generic.List`1[[System.Data.SqlClient.SqlParameter, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] to a known managed provider native type.

 

通过搜索

https://stackoverflow.com/questions/9149919/no-mapping-exists-from-object-type-system-collections-generic-list-when-executin

 看到后面的ToList() 改成 ToArray()

 

                    var param = new List<SqlParameter>();
                    param.Add(new SqlParameter("@StartTime", DateTime.Parse(req.StartTime)));
                    param.Add(new SqlParameter("@EndTime", DateTime.Parse(req.EndTime)));
                    
                    response.List = _ctx.Database.SqlQuery<ReceiveSummeryItem>(sql, param.ToArray()).ToList();
                    response.TotalCount = response.List.Count();

结果好了,真神奇!

搞定!

posted @ 2017-05-23 12:58  0539  阅读(5055)  评论(0编辑  收藏  举报