【发布时间】:2015-09-18 12:17:07
【问题描述】:
我在 CommentService 中使用了两个存储库。
_commentRepository
_userRepository
使用 _commentRepository.GetAll() 函数,我获得了包含以下信息的所有 cmets 的列表:[Id]、[Content]、[UserId]。
我正在尝试创建一个列表,其中包含所有 cmets 和一些可通过 _userRepository 获得的匹配用户信息,并将其存储在 DTO 中。
public ListOutput<CommentUserDto> GetCommentsWithUserInformation()
{
var comments = _commentRepository.GetAll();
// TODO: Add comment and user information to CommentUserDto.
return new ListOutput<CommentUserDto>
{
Items = Mapper.Map<List<CommentUserDto>>(comments)
};
}
我怎样才能做到这一点?
我发现的一些可能的想法:
- 创建 _commentUserRepository
- 使用 include 以某种方式连接两个表(我使用的是 E.F.)
- 在我的域层中创建一个负责组合逻辑的管理器。
编辑:
评论模型:
public class Comment
{
public virtual string Content { get; set; }
public virtual DateTime CreationTime { get; set; }
public virtual long UserId { get; set; } // Id of User that posted Comment (always filled in)
}
用户模型:
public class User {
public virtual string Name { get; set; }
public virtual string Surname { get; set; }
public virtual string Email { get; set; }
public virtual string Password { get; set; }
}
CommentUserDto: // 视图的可访问类
public class CommentUserDto {
public string Content { get; set; } // from comment
public DateTime CreationTime { get; set; } // from comment
public string PosterName { get; set; } // from user
public string PosterSurname { get; set; } // from user
}
【问题讨论】:
-
你在使用实体框架吗?
-
我个人喜欢有一个用于评论和用户的存储库,然后在存储库之上我有我的服务类,它为我提供了来自这两个存储库的组合对象。如果您关心使用实体框架,Include 也是一个选项
-
是的,我是(将澄清问题)。
-
您的评论库返回什么对象?您可以发布 EF 生成的模型吗?如果你正确连接了评论和用户,你应该有从 cmets 到用户的连接,反之亦然。我认为这并不像您在这里介绍的那么复杂。
标签: .net asp.net-mvc asp.net-mvc-5 repository-pattern data-transfer-objects