MVC Core 3 FromSqlRaw parameters not working as expected

眉间皱痕 提交于 2021-02-11 15:36:34

问题


Has anyone else run into the issue of FromSqlRaw parameters not working as expected? There is a Gotcha to be aware of.

With the latest MVC Core 3 DbContext I added a stored procedure but could not get the FromSqlRaw call to correctly evaluate parameters.

    SqlParameter[] parameters = {
        new SqlParameter("DateFrom", dateFrom),
        new SqlParameter("DateTo", dateTo),
        new SqlParameter("Sort", sort),
        new SqlParameter("Aggregation", aggregation)
            };


return await sp_Visits.FromSqlRaw("EXECUTE dbo.sp_Visits @DateFrom, @DateTo, @Aggregation, @Sort", parameters).ToListAsync();

alter PROCEDURE dbo.sp_Visits 
     @DateFrom      date
    ,@DateTo        date
    ,@Sort          nvarchar(50)
    ,@Aggregation   nvarchar(20)
    AS

回答1:


I found that the following worked OK:

return await sp_Visits.FromSqlRaw("EXECUTE dbo.sp_Visits @DateFrom=@DateFrom, @DateTo=@DateTo, @Aggregation=@Aggregation, @Sort=@Sort", parameters).ToListAsync();

Then I noticed that the parameter array definition order is different from the SQL EXECUTE parameter order. It appears that creating named parameters does not imply the names will be matched by FromSqlRaw but instead appears to use the parameters as ordered. I've been so used to C# Database code matching up the names over the years that I didn't give it a thought until this code did not work.

After matching the order of parameters, the original code works

SqlParameter[] parameters = {
            new SqlParameter("DateFrom", dateFrom),
            new SqlParameter("DateTo", dateTo),
            new SqlParameter("Aggregation", aggregation),
            new SqlParameter("Sort", sort)
                };


来源:https://stackoverflow.com/questions/62719267/mvc-core-3-fromsqlraw-parameters-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!