What type to return when querying multiple entities in Repository layer?

这一生的挚爱 提交于 2019-12-03 12:21:14
Peter Porfy

If those entities are related and you query all of them in one place then you should try to find an aggregate root of them in your domain model or if it doesn't exist yet you should introduce a new one, as you said in the first option. This is not wrong until it makes sense. It should model a domain concept and you probably have one because you created that repository method.

If those entities are not related (well, probably related in some way, but not that tightly as above) and you just want to get them in one go then you should handle that in the service layer where you can use multiple repositories and compose a result object.

You probably heard of the concept of navigation properties and eager loading but I write it here because it may be another answer to your question (I don't see your domain model)

I wouldn't go with your third suggestion (create viewmodels in the repository) because it breaks the separations.

Different entities can relate to each other whithout one of them being an aggregate root. Services are used to these kind of queries. I usually do something like this:

public class MyService
{
    IEnumerable<UserWithMessages> Find()
    {
        var messages = _messageRepository.FindAll();
        var userIds = _messages.Select(x => x.UserId).Distinct().ToArry();
        var users = _userRepository.Find(userIds);
        return users.Select(x => new UserWithMessages(x, messages.Where(x => x.UserId == x.Id));
    }
}

It's just two DB queries which can utilize indexes in the DB. So It should be pretty fast.

I suggest you to use DTO (Data Transfer Objects) for this purpose. It's a common practice to separate your service layer from the view, and DTOs allow you to share only the important information necessary for the views.

There are various ways to implement this part of the system depending of the size of the system. In small systems you can use extension methods to map your POCO entities in data transfer objects

I suggest you take a look to "AutoMapper". I think this will be really usefull for you

http://www.codeproject.com/Articles/61629/AutoMapper

http://lostechies.com/jimmybogard/2009/01/23/automapper-the-object-object-mapper/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!