samedi 27 mai 2017

Aggregate fields in DTO

I have some architectural/pattern question. Suppose that i have a domain model with two classes. I use Code First and Repository Pattern. (To make it more simple in the example I use only fields, not properties)

public class Person {
    public int Id;
    public string Name;
    public string Surname;
    public virtual ICollection<Pet> Pets;
}
public class Pet {
    public string Name;
    public int BirthYear;
    public int OwnerId;
    public Person Owner;
}

I also have PersonDto, and PetDto classes, with the only difference, that Pets field in PersonDto is a simple List. I use Automapper to transform model classes to dto. Dto are next sent to the client through REST Api. Now, what if on some view I need to show for every Person its Name, Surname and PetCount (lets assume that there are so many pets that it would make it very inefficient to pull them from database and simply count them on the view).

Now - what would be the correct approach to introduce PetCount. Should I put this field in the PersonDto as well as in the Person class, and prevent it from creating column in the database (it doesn't seem right for me). Or maybe I should only create PetCount field in PersonDto - but then when to count this value, in the repository method or maybe while mapping (the latter also doesn't seem right for me). Another question is if I should create an extra field in PetDto, or maybe I should inherit PersonDto with PersontWithPetCountDto, or maybe I should create PersontWithPetCountDto class without inheritance, but with PetCount field and all the fields from PersonDto

Aucun commentaire:

Enregistrer un commentaire