Large Entity and ViewModel Mapping

360 Views Asked by At

I have a very large entity with a few hundred properties. I have a repository that I use to select this all of the entities and returns an IEnumerable of the entity.

In my controller I then use automapper to map to an index ViewModel of this entity and it only uses two of the properties of the entity in the ViewModel. It takes quite a long time to return compared to a select of the two properties. It would seem that it is selecting all of properties of the entity and then just using two of them.

What would be the recommended way of doing this. Do I need to create the view model in the repository?

Graeme

1

There are 1 best solutions below

2
On BEST ANSWER

You can pass a DTO or different model.

public class LargeEntityDto
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

Then in your repository

public IEnumerable<LargeEntityDto> GetLargeEntityDtos()
{
   return context.LargeEntities
      .Select(e => new LargeEntityDto { Foo = e.Foo, Bar = e.Bar});
}