Entity Framework Include Without Attached Properties

I have two related objects called DataTag and TagSource that look like this:

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 allow the user to include navigation properties through the URL, for example, "/ api / DataTags? Include = TagSource". The problem is that when I turn on TagSource, it also includes a set of DataTags in this object, which I don’t want if the user does not specify it (for example, "/api/DataTags?Include=TagSource.DataTags." To stop Is this property due to loading when I turn on TagSource? I tried to make virtual objects and make lazy loading globally, but it didn’t work. The reason I don't mark them virtual is because I use AutoMapper and I just want to include the navigation properties that the user specifies.

0
source share
2 answers

As in the comments, you need to create a DTO object. There is a good article here that details how to do this using WebAPI

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

Change

The problem with this is that you will need many different DTO objects for every possible result that can become messy. If your return type is JSON, you can add this attribute to your properties:

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

First: Apologies for my English.

Secondly: I had the same problem with the first code model, which creates foreign keys in this way: public virtual Collection<Object> Objects {get; set;} public virtual Collection<Object> Objects {get; set;}

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

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

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

0
source

All Articles