0
votes

Is it possible to eagerly load related entities, but to not have the related entities of the related entities be loaded?

In my case, I have a set of flags to determine which related entities should be loaded:

[Flags]
public enum FooRetrievalOptions
{
    None = 0,
    Bar = 1,
    Baz = 2,
    All = Bar | Baz
}

I create an IQueryable<Foo> and successively .Include depending on which flags have been set.

IQueryable<Foo> query = context.Foos;

if (fooRetrievalOptions.HasFlag(FooRetrievalOptions.Bar))
{
    query.Include(f => f.Bar);
}

if (fooRetrievalOptions.HasFlag(FooRetrievalOptions.Baz))
{
    query.Include(f => f.Baz);
}

List<Foo> foos = query.ToList();

The problem with this is that it can create cycles when serializing depending on the navigation properties on Bar and Baz.

I simply want to load associated entities in one database hit without their own related entities being loaded as well. Is this possible?

1
What library are you using to serialize your objects ? - Maxime
DataContractSerializer. I could use the IsReference = true to handle the cycles, but it seems like that would result in fairly large XML. - bbush
Lazy loading is on the context is disabled. That's why I am specifying what related entities to load eagerly. - bbush
What about the IgnoreDataMemberAttribute if you are using .NET 4.5 ? - Maxime
That wouldn't help in this case. The attribute would be required in some instances but not all, depending on the flags. - bbush

1 Answers

0
votes

Create a Data Transfer Object (DTO) and copy the values you want into that before passing that on for serialisation. It's common to do this kind of thing when developing APIs to help deal with EF circular references and only return what's needed by the consumer.

edit: In regards to the seemingly tedious manual mapping of all the attributes, there are solutions to help with this such as Automapper: http://automapper.org/