0

I am using Entity Framework 5.0 in .NET 4.5 in a Web API service to provide REST data to client. I would like to return to clients the results of a shallow query of an entity with a relationship. I want to do this over the entire collection of entities, not just one of them (which is why Select shallow object from database, dropping all references from foreign keys and Entity Framework - Select with or without relationships do not directly answer this question). Based on what I saw in those I currently have:

    public IEnumerable<JournalEntryType> GetAllJournalEntryTypesShallow() {
        // this is stupid but I can't find a better way
        var results = new List<JournalEntryType>();
        using (var context = new SecondaryContentTrackingEntities()) {
            foreach (var result in 
                from j in context.JournalEntryTypes
                select j) {
                result.JournalEntries.Clear();
                results.Add(result);
            }
        }
        return results;
    }

This is then serialized automatically for me and is returned to the client. But this is really horrible looking, and potentially pulls down data I immediately throw away (although I suspect that's not true if I leave lazy loading on - I have not researched under the hood enough to know yet). I keep thinking there has to be a better way to tell EF "don't bother traversing the relationship in this case."

Alternatively, is there a good way to get the automatic serialization to be shallow without having to write my own? I know I can write my own, but it seems like a bunch of code just to do something relatively straightforward.

I don't think EF lazy loading or not doesn't help because I'm iterating over all of them anyway (they are being serialized) so eventually everything gets touched with the children getting pulled in.

I could just delete the references in the designer, but then I lose them for times when I actually want them, and I will have to do it every time I update from the database, so that's not ideal either.

Is there a smarter way to do this?

4

0 回答 0