Search code examples
c#entity-frameworkc#-4.0entity-framework-4.1entity-framework-4.3

Dynamic Include statements for eager loading in a query - EF 4.3.1


I have this method:

public CampaignCreative GetCampaignCreativeById(int id)
        {
            using (var db = GetContext())
            {
                return db.CampaignCreatives
                    .Include("Placement")
                    .Include("CreativeType")                    
                    .Include("Campaign")
                    .Include("Campaign.Handshake")
                    .Include("Campaign.Handshake.Agency")
                    .Include("Campaign.Product")
                    .AsNoTracking()
                    .Where(x => x.Id.Equals(id)).FirstOrDefault();
            }
        }

I would like to make the list of Includes dynamic. I tried:

public CampaignCreative GetCampaignCreativeById(int id, string[] includes)
        {
            using (var db = GetContext())
            {
                var query = db.CampaignCreatives;

                foreach (string include in includes)
                {
                    query = query.Include(include);
                }

                return query.AsNoTracking()
                    .Where(x => x.Id.Equals(id)).FirstOrDefault();                    
            }
        }

But it didn't compile. I got this error:

Cannot implicitly convert type 'System.Data.Entity.Infrastructure.DbQuery' to 'System.Data.Entity.DbSet'. An explicit conversion exists (are you missing a cast?)

Does anyone know how to make the list of Includes dynamic?

Thanks


Solution

  • Make the query variable queryable:

    public CampaignCreative GetCampaignCreativeById(int id, string[] includes)
    {
        using (var db = GetContext())
        {
            var query = db.CampaignCreatives.AsQueryable();
            foreach (string include in includes)
            {
                query = query.Include(include);
            }
    
            return query
                .AsNoTracking()
                .Where(x => x.Id.Equals(id))
                .FirstOrDefault();                    
        }
    }