WebApi Speed for Returning Related Entities

时间:2016-10-20 12:57:03

标签: c# entity-framework asp.net-web-api

My WebApi is working with a lot of internal references between my objects and i'm wondering what would be less costly for the application. I'm using EF database first so i don't have access to the generated classes (I know i can edit them but it's not that smart).

For example, i have some areas where i will have 5 relations, and those relations are deep but i don't want to return them all the time to the user because i won't use all that data, sometimes i just need the parent object and to work that around i'm using AutoMapper and creating some ViewModels where i make a copy of my object.

On some point on my Api that i only want to return some entities i would start the AutoMapper and tell him what he should ignore for that case.

My problem is as i said, i have a lot of data, this system is going to be used for 15k - 20k users. Is the AutoMapper ignoring the data be a bottleneck up ahead ? If so would be better i use some other alternative ?

If this isn't the best option, what else could i use ?

This is an example of how i'm working:

Controller:

public async Task<EventVM> Get(int id)
{
    var event = await eventService.Get(id);

    return event;
}

Service:

public async Task<EventoVM> Get(int id)
{
    var event = await _context.Event.FindAsync(id);

    return event;
}

Also i checked on my configuration, Lazy Loading is enabled.

1 个答案:

答案 0 :(得分:2)

Some of the things in your initial post are not clear at all.

You say you use code first but don't have access to generated classes. Well, if you use code first there won't be generated classes, but you must have some classes initially from which your sql tables get generated, right?

As a rule of thumb, do not use anything from EF in your WebApi. Have your Api return only the data and properties you need for each endpoint. This means creating another set of classes, tipically DTOs which are much lighter, don't have any methods only public properties with exactly the data you need. Yes, you will need an extra step in between to transform the data, but that is absolutely fine.

This should help you get started, just remember the important rule : return exactly what you need, nothing more, nothing less.