locked
EF Including Other Entities (Generic Repository pattern) RRS feed

  • Question

  • Hi everyone,
    I am using the Generic Repository pattern on top of Entity Framework Code First. Everything was working fine until I needed to include more entities in a query. I got to include one entity successfully, but now I can't figure out how to include multiple entities. Check out what I've got so far:

        public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
        {
            var entityName = GetEntityName<TEntity>();
            return _objectContext.CreateQuery<TEntity>(entityName);
        }
        
        public IList<TEntity> GetQueryWithInclude<TEntity>(string toInclude) where TEntity : class
        {
            var entityName = GetEntityName<TEntity>();
            return _objectContext.CreateQuery<TEntity>(entityName).Include(toInclude).ToList();
        }
        
        private string GetEntityName<TEntity>() where TEntity : class
        {
            return string.Format("{0}.{1}", _objectContext.DefaultContainerName, _pluralizer.Pluralize(typeof(TEntity).Name));
        }
    
    
    What I tried to do but didn't work was pass in an array of strings into a function, then try to "append" the includes on top of the query. I was wondering what if I called the GetQueryWithInclude and passed an entity name (actually a navigation property) at a time to aggregate the results of the query, but I'm worried this might duplicate the results of the query on each call... What do you think would be the best way to get this to work?
    Here's an example of what I'm trying to achieve:
        public IQueryable GetQueryWithIncludes(string[] otherEntities)
        {
            var entityName = GetEntityName<TEntity>();
            //now loop over the otherEntities array 
            //and append Include extensions to the query
            //so inside the loop, something like: 
            _objectContext.GetQuery<TEntity>(entityName).Include(otherEntities[index]);
        }
    
    Thanks in advance!


    Monday, March 21, 2011 5:47 PM

Answers