Search code examples
c#entity-frameworkiqueryablenavigation-properties

Include several navigation properties with Include(string) method


For the first, I'm trying to avoid direct link to EntityFramework in my assembly, so I can't use System.Data.Entity namespace in client code, only in interface implementation class.

I have interface

    public interface IEntitySource<T>
        where T : class
    {
        ...
        IQueryable<T> WithProperties(params string[] properties);
        ...
    }

and it's EF implementation:

public class EfEntitySource<T> : IEntitySource<T>
    where T : class
{
    public IQueryable<T> WithProperties(params string[] properties)
    {
        IQueryable<T> queryable = this.DbSet;
        foreach (var property in properties)
        {
            queryable = this.DbSet.Include(property);
        }

        return queryable;
    }
}

and client code:

public IEnumerable<ContentChangeHistory> GetContentActivityAtGroup(Guid groupId)
{
    var groupActivity = this.ContentChangeHistorySource
        .WithProperties("ContentPost", "ContentItem", "SystemUser")
        .Where(cch => cch.ChangeGroupId == groupId);
    return groupActivity;
}

but, the code, that executes GetContentActivityAtGroup method, returns ContentChangeHistory collection with only latest navigation property initialized, e.g. SystemUser.

some code modifications, like this:

public IQueryable<T> WithProperties(params string[] properties)
{
    foreach (var property in properties)
    {
        this.DbSet.Include(property);
    }

    return this.DbSet;
}

gave no results


Solution

  • Change

    queryable = this.DbSet.Include(property);
    

    to

    queryable = queryable.Include(property);