c# - 类列表之间的映射和转换
问题描述
我有一个查询检索多个用户,其中用户可能订阅了多个包含 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; }
}
解决方案
推荐阅读
- android - 数据在领域数据库中插入两次
- apache - 阿帕奇默认目录
- python - 使用 bs4 和请求访问嵌套 div
- angular - 角翻译实现
- php - Laravel:如何在没有数据库的情况下对用户进行身份验证
- css - Eclipse:错误地将 CSS 文件视为 XML
- python - pyinstaller制作的exe文件在其他电脑上有延迟
- python - 隐藏图形而不是重叠
- cordova - 升级到 wkwebview 后没有加载 Angular 谷歌地图
- android - Android:A/libc:致命信号 11 (SIGSEGV),代码 1,tid 18372 中的故障地址 0x8