我正在使用 EF DbContext SqlQuery 来获取使用 PagedList (https://github.com/TroyGoode/PagedList)的分页对象列表,我收到以下错误:
“SqlParameter 已被另一个 SqlParameterCollection 包含”
这是我的存储库代码:
var db = (DbContext)DataContext;
const string sqlString =
@"
WITH UserFollowerList
AS
(
SELECT uf.FollowId
FROM UserFollow uf
WHERE uf.UserId = @UserId
)
SELECT * FROM UserFollowerList uf
INNER JOIN [User] u ON uf.FollowId = u.UserId
WHERE IsDeleted = 0
"
;
var userIdParam = new SqlParameter("UserId", SqlDbType.Int) {Value = userId};
var userList =
db.Database.SqlQuery<User>(sqlString, userIdParam)
.ToPagedList(pageIndex, pageSize);
return userList;
但是当我在 SqlQuery 语句上调用 ToList 扩展时,它工作正常:
var userList = db.Database.SqlQuery<User>(sqlString, userIdParam).ToList();
分页列表代码:
private PagedList(IQueryable<T> source, int pageIndex, int pageSize)
{
TotalItemCount = source.Count();
PageSize = pageSize;
PageIndex = pageIndex;
PageCount = TotalItemCount > 0 ? (int)Math.Ceiling(TotalItemCount / (double)PageSize) : 0;
HasPreviousPage = (PageIndex > 0);
HasNextPage = (PageIndex < (PageCount - 1));
IsFirstPage = (PageIndex <= 0);
IsLastPage = (PageIndex >= (PageCount - 1));
ItemStart = PageIndex * PageSize + 1;
ItemEnd = Math.Min(PageIndex * PageSize + PageSize, TotalItemCount);
// add items to internal list
if (TotalItemCount > 0)
Data = pageIndex == 0 ? source.Take(pageSize).ToList() : source.Skip((pageIndex) * pageSize).Take(pageSize).ToList();
}
我已经解决了以下问题,但没有成功:
var param = new DbParameter[] { new SqlParameter { ParameterName = "UserId", Value = userId }
我可以做些什么来解决我遇到的错误?