如何在相关表中进行分页并映射到精巧的查询?

时间:2016-11-25 08:24:06

标签: c# sql relationship paging dapper

我的数据库中有两个表,如下表所示。

[用户]。[信息]

TABLE_SCHEMA    TABLE_NAME  COLUMN_NAME
User    Info    Id
User    Info    UniqueId
User    Info    Name
User    Info    Email
User    Info    CompanyInfoId
User    Info    UserTypeId
User    Info    LanguageId
User    Info    InsertedBy
User    Info    InsertedOn
User    Info    UpdatedBy
User    Info    UpdatedOn
User    Info    DeletedBy
User    Info    DeletedOn
User    Info    IsDeleted

[用户]。[类型]

TABLE_SCHEMA    TABLE_NAME  COLUMN_NAME
User    Type    Id
User    Type    UniqueId
User    Type    Name
User    Type    CompanyInfoId
User    Type    LanguageId
User    Type    InsertedBy
User    Type    InsertedOn
User    Type    UpdatedBy
User    Type    UpdatedOn
User    Type    DeletedBy
User    Type    DeletedOn
User    Type    IsDeleted

我想在sql中为我的查询做分页。一张桌子没问题。我可以这样做:

DECLARE @Page       AS INT = 1
DECLARE @PageSize   AS INT = 10
SELECT TOP (@PageSize) Paged.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY Id) AS Row, * FROM [User].[Info]) AS Paged WHERE Row > (@Page - 1) * @PageSize

但是我在我的项目中使用DAPPER,我希望得到[用户]。[信息]和[用户]。[类型]来自db,如上所述。

这是我的标准内连接查询:

SELECT TOP 10 * FROM [User].[Info] ui INNER JOIN [User].[Type] ut ON ui.UserTypeId = ut.Id

我尝试使用此查询进行分页:

DECLARE @Page       AS INT = 1
DECLARE @PageSize   AS INT = 10
SELECT TOP (@PageSize) Paged FROM ( 
    SELECT ROW_NUMBER() OVER (ORDER BY ui.Id) AS RowNumber, ui.*, ut.* FROM [User].[Info] ui INNER JOIN [User].[Type] ut ON ui.UserTypeId = ut.Id
) AS Paged WHERE RowNumber > (@Page - 1) * @PageSize

结果我得到一个错误:

Msg 8156, Level 16, State 1, Line 102
The column 'Id' was specified multiple times for 'Paged'.
Msg 207, Level 16, State 1, Line 100
Invalid column name 'Paged'.

由于表具有相同的命名列。如何解决这个问题?

为什么我要这样做?

在dapper调用结果中,我想在EntityFramework中实现从UserInfo实体到达UserType以及如何在相同的列名中映射到我的查询结果实体而没有问题。

这是我现在的短暂召唤:)

    public IEnumerable<UserInfo> All()
    {
        using (IDbConnection db = CreateConnection())
        {
            var sql = "MY SQL QUERY WITH PAGING";
            var command = db.Query<UserInfo, UserType, UserInfo>(sql, (userInfo, userType) =>
            {
                userInfo.UserType = userType;
                return userInfo;
            });

            return command;
        }
    }

我看了很多样品,但我无法解决。请帮忙!

enter image description here

1 个答案:

答案 0 :(得分:1)

您也可以尝试将查询更改为:

DECLARE @Page       AS INT = 1
DECLARE @PageSize   AS INT = 10

SELECT 
    ui.*, 
    ut.* 
FROM [User].[Info] ui 
   INNER JOIN [User].[Type] ut ON ui.UserTypeId = ut.Id
ORDER BY ui.Id
OFFSET (@Page - 1) * @PageSize ROWS
FETCH NEXT @PageSize ROWS ONLY

我不确定DAPPER是否可以,但它解决了SQL Server错误