问题
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