0
votes

I have two related entities called DataTag and TagSource that look like the following:

public class DataTag : BaseModel
{
    [Column("DataTagId")]
    public override Guid ID { get; set; }
    public string Tag { get; set; }

    public Guid TagSourceId { get; set; }
    public TagSource TagSource { get; set; }
}

public class TagSource : BaseModel
{
    [Column("TagSourceId")]
    public override Guid ID { get; set; }
    public string Description { get; set; }
    public bool IsInternal { get; set; }
    public string Source { get; set; }

    public ICollection<DataTag> DataTags { get; set; }
}

I am allowing the user to Include the navigation properties through the url like "/api/DataTags?Include=TagSource". The problem is when I include the TagSource, it also includes the collection of DataTags in that object which I don't want unless the user specifies it (For example "/api/DataTags?Include=TagSource.DataTags". Is there any way to stop that property from being loaded when I include the TagSource? I have tried making the properties virtual and turning lazy loading off globally but that didn't work. The reason I haven't marked them virtual is because I am using AutoMapper and I only want to include the navigation properties that the user specifies.

2
Project it to something else. Your problem is the WebAPI serializes the whole object you return. - Casey
Use a DTO with just the data you want to return to the user - Chris
Could you show the action method that the URL maps to? I don't understand how disabling lazy loading still loads navigation properties. - Gert Arnold

2 Answers

0
votes

As in the comments you need to create a DTO object. There is a good article here detailing how to do this with WebAPI

http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-5

Edit.

The problem with this is you will need a lot of different DTO objects for each possible outcome which could become messy. If your return type is JSON you can add this attribute to your properties:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
0
votes

Firstly : Apologies for my English.

Secondly : I had the same issue with a code first database model that creates foreign keys this way : public virtual Collection<Object> Objects {get; set;}

and I found a workaround by setting the property setter as private:

public virtual Collection<Object> Objects {get; private set;}

Then the EF cannot populate the Objects collection because with a private set you can only assign a value in constructors.