edobry
edobry

Reputation: 335

ASP.NET MVC WebApi - Do not expose navigation properties

I have a WebApi project, and I am using the Entity Framework to bind to my database. Most of my Models have navigation properties on them, and when I return them from my controllers, they appear in the JSON string. Is it possible not to expose them?

Upvotes: 1

Views: 564

Answers (2)

frennky
frennky

Reputation: 13934

You should consider using View Models and serving them instead of your Models. To help you with that you can use mapping libraries such as AutoMapper.

Upvotes: 1

Andy T
Andy T

Reputation: 9881

In various JSON serializers there are attributes you can set on your properties to prevent them from being serialized.

Another option would be to create DTOs with the sole purpose of using them as returned types for the WebAPI. More work, but you'll have complete control over what is sent.

Upvotes: 1

Related Questions