0

CommentService で 2 つのリポジトリを使用しています。

_commentRepository
_userRepository

_commentRepository.GetAll() 関数を使用して、[Id]、[Content]、[UserId] の情報を含むすべてのコメントのリストを取得します。

すべてのコメントと、_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)
    };
}

どうすればこれを機能させることができますか?

私が見つけたいくつかの可能なアイデア:

  1. _commentUserRepository の作成
  2. include を使用して 2 つのテーブルを結合する (私は EF を使用しています)
  3. ロジックの結合を担当するドメイン レイヤーにマネージャーを作成します。

編集:

コメントモデル:

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
}
4

1 に答える 1

1

You don't need to do any of the three options you mention. If you have a navigation property from Comment to User, you can handle that in your mapping. Something like:

Mapper.CreateMap<Comment, CommentUserDto>().ForMember(dest => dest.UserName, opts => opts.MapFrom(src => src.User.UserName));

If you don't have a navigation property, then after your initial mapping, loop through the list of dto objects and call the appropriate _userRepository method to get the user information and populate the appropriate members of the dto object that way.

Edit

After seeing your models, what I would do (assuming a navigation property is not an option) is something like this:

var comments = _commentRepository.GetAll();

var results = new List<CommentUserDto>();

foreach(Comment comment in comments)
{
   var user = _userRepository.Get(comment.userId);
   var commentUserDto = new CommentUserDto
   {
      Content = comment.Content,
      CreationTime = comment.CreationTime,
      PosterName = user.Name,
      PosterSurname = user.Surname
   }

   results.Add(commentUserDto);
}

return results;
于 2015-09-18T12:47:35.590 に答える