首页 > 解决方案 > 类列表之间的映射和转换

问题描述

我有一个查询检索多个用户,其中用户可能订阅了多个包含 Id 和名称的 UserTeamNotifications。我正在尝试获取这些用户的列表以及他们订阅的通知列表。这样我的 User.cs 类将有一个 NotificationTeam 对象列表。

string sql = @"
SELECT
    u.UserId,
    u.UserName,
    tn.TeamId AS NoticationTeamId,
    tn.TeamName AS NoticationTeamName
FROM Users u
LEFT JOIN Teams tu ON tu.TeamId = u.TeamId
LEFT JOIN UserTeamNotifications n ON n.UserId = u.UserId
LEFT JOIN Teams tn ON tn.TeamId = n.TeamId
";
            return connection.Connection.Query<DbUser>(sql)
                .GroupBy(u => u.UserId)
                .Select(u => UserMapper.Map(u.First(), u.Select(n => new DbTeamNotification
                {
                    TeamId = n.NotificationTeamId,
                    TeamName = n.NotificationTeamName
                }).ToList()))
                .ToList();

但是,我无法将 TeamNotifications 映射回我的控制器。出现错误:无法从“System.Collections.Generic.List<SBIS.Data.DbObjects.DbTeamNotification>”转换为“System.Collections.Generic.List<SBIS.Models.Users.NotificationTeam>”。在下面的映射中。

用户映射器.cs

    internal class UserMapper
    {
        public static User Map(DbUser source, List<DbTeamNotification> notifications)
        {
            return source == null ? null : new User(
                userId: source.UserId,
                name: source.UserName,
                notificationTeams: notifications
                );
        }
    }

用户.cs

public sealed class User
{
    public User(long userId, string name, List<NotificationTeam> notificationTeams)
    {
        m_userId = userId;
        m_name = name;
        m_notificationTeams = notificationTeams;
    }

    public long UserId => m_userId;
    public string UserName => m_name;
    public List<NotificationTeam> NotificationTeams => m_notificationTeams;

    private readonly long m_userId;
    private readonly string m_name;
    private readonly List<NotificationTeam> m_notificationTeams;
}

数据库用户.cs

internal sealed class DbUser
{
    public long UserId { get; set; }
    public string UserName { get; set; }
    public long NotificationTeamId { get; set; }
    public string NotificationTeamName { get; set; }
}

通知团队.cs

public sealed class NotificationTeam
{
    public NotificationTeam(long teamId, string teamName)
    {
        m_teamId = teamId;
        m_teamName = teamName;
    }

    public long TeamId => m_teamId;
    public string TeamName => m_teamName;

    private readonly long m_teamId;
    private readonly string m_teamName;
}

DbTeamNotifications.cs

internal class DbTeamNotification
{
    public long TeamId { get; set; }
    public string TeamName { get; set; }

}

标签: c#asp.net-mvcmapping

解决方案


推荐阅读