-1

I have an entity framework class (Document) with a child (Provider) that has an array of objects (Documents). I want to pull my Document class and include it's Provider child but not include the Provider's array of Document objects. I can't remove the documents property from Provider because I do need the documents array at other times. How do I pull the documents with providers, but exclude each providers documents array with linq?

Here's my class structure:

Document {
    public string DocumentName { get; set; }
    public virtual Provider Provider { get; set; }
}
Provider {
    public string Name { get; set; }
    public virtual ICollection<Document> Documents { get; set; }
}

I'm trying to get my document objects using linq like this:

db.Documents.Where(x => x.Id == Id)
.Include(x => x.Provider)
.ToList();

And here's what the result looks like:

[{
    'DocumentName': 'document_one.pdf',
    'Provider': {
        'Name': 'Jim Smith',
        'Documents': [
            {
                'DocumentName': 'document_one.pdf'
            },
            {
                'DocumentName': 'document_two.pdf'
            },
        ]
    }
}]

So how do I accomplish getting this exact result set, just without the Provider.Documents array being populated? Again, I can't remove the Documents property from the Provider class because I need it at other times.

Tyler Jones
  • 1,202
  • 4
  • 17
  • 36

2 Answers2

0

Assuming this is only for Get's and not for saving just Iterate the documents and set them to null.

var documents = db.Documents.Where(x => x.Id == Id)
.Include(x => x.Provider)
.ToList()

documents.ForEach(x => x.Provider.Documents = null);

My guess is you don't want this because it's being exposed to the client during serialization, If that's the case you probably should be creating A DTO

johnny 5
  • 16,589
  • 46
  • 82
  • 156
0

I found a blog post and a SO answer I combined to answer my question. I have to create a special DTO for the documents in which the Provider property is also a special DTO for the providers. The DTO's can exclude the properties then I have to do a select statement to convert the database classes into the DTO's like this:

db.Documents.Where(x => x.Id = Id)
.Include(x => x.Provider)
.Select(x => new DocumentDTO{
    DocumentName = x.DocumentName,
    Provider = new ProviderDTO{
        Name = x.Provider.Name
    }
})
.ToList();

Blog post here.
SO answer here.

Tyler Jones
  • 1,202
  • 4
  • 17
  • 36