hyperN
hyperN

Reputation: 2754

Web.api Get method to show only selected properties from entity

Let's say I have 3 entities: Advert, User and UserRole. And in Web.Api project GetAllAdverts method.

public IEnumerable<Advert> GetAllAdverts()
    {
        return repository.GetAll<Advert>();

    } 

When i enter url ../api/advert I get JSON with all Adverts and data about adverts, but I get all data about user and user role too.

How can I get for example all advert data and only UserName form entity User ?

Is this done by creating DTOs ?

Thanks in advance !

Upvotes: 0

Views: 153

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109119

Using DTO's is usually a good idea. It is more work, but it gives you full control and it abstracts out peculiarities of a specific data layer.

In your case, if you really only want UserName you even have to use a DTO, because it is impossible to partly load the User as navigation property from Advert.

If it does not matter that you see all properties of User except its navigation properties (like role), you may also consider to (temporarily) turn off lazy loading for the context in the repository and eager load Advert.User by using Include.

Upvotes: 1

Related Questions