Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Including Other Entities (Generic Repository pattern)

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?

Thanks in advance!

UPDATE:

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]);
}
like image 625
Kassem Avatar asked Mar 21 '11 10:03

Kassem


People also ask

Do we need repository pattern with Entity Framework?

No, the repository/unit-of-work pattern (shortened to Rep/UoW) isn't useful with EF Core. EF Core already implements a Rep/UoW pattern, so layering another Rep/UoW pattern on top of EF Core isn't helpful.

What is generic repository pattern in Entity Framework?

The generic repository pattern implements in a separate class library project. It uses the "Code First" development approach and creates a database from a model, using migration. This article demonstrates a sample Application, which has one too many relationships in ASP.NET Core with Entity Framework Core.

What is the right way to include a repository into a controller?

By taking advantage of dependency injection (DI), repositories can be injected into a controller's constructor. the following diagram shows the relationship between the repository and Entity Framework data context, in which MVC controllers interact with the repository rather than directly with Entity Framework.

What is generic repository in Entity Framework?

I often see colleagues using in projects their own implementation of repositories on top of the ones existing in Entity Framework. Generic Repository as an attempt to disregard a particular ORM.

What is the use of client objects in Entity Framework?

Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Entity Framework provides us with the actual implementation of the Repository patterns: DbSet<T> and UnitOfWork: DbContext.

Is the generic repository pattern a good fit for your project?

As with everything, the generic repository pattern has its pros and cons. You are the one to decide if it’s a good fit for your project. You can always use it only for parts of your application, you don’t have to go all in with generic repository pattern!

Is it possible to get order items from address in EF?

It is available in EF 4.1 assembly. If you don't want to reference that assembly in your upper layers create wrapper extension method in your data access assembly. You will use it for example like: This query will load all customers with their addresses and orders and every order will contain its order items.


3 Answers

Use just the Include extension on IQueryable. It is available in EF 4.1 assembly. If you don't want to reference that assembly in your upper layers create wrapper extension method in your data access assembly.

Here you have example:

public static IQueryable<T> IncludeMultiple<T>(this IQueryable<T> query, params Expression<Func<T, object>>[] includes)
    where T : class
{
    if (includes != null)
    {
        query = includes.Aggregate(query, 
                  (current, include) => current.Include(include));
    }

    return query;
}

You will use it for example like:

var query = context.Customers
                   .IncludeMultiple(
                       c => c.Address,
                       c => c.Orders.Select(o => o.OrderItems));

This query will load all customers with their addresses and orders and every order will contain its order items.

like image 191
Ladislav Mrnka Avatar answered Oct 20 '22 02:10

Ladislav Mrnka


//I have included the bare minimum here. Below is how to use it.

     IQueryable<File> xg= UnitOfWork.Files.GetAllLazyLoad(d => d.FileId == 1, 
            r => r.FileCategory);
//where r.FileCategory is a navigational property.

//Interface


    namespace Msh.Intranet.Repository.GenericRepoPattern
    {
        public interface IRepository<T> where T:class
        {

            IQueryable<T> GetAllLazyLoad(Expression<Func<T, bool>> filter, params Expression<Func<T, object>>[] children);

        }
    }



        namespace Msh.Intranet.Repository.GenericRepoPattern
        {
            /// <summary>
            /// The EF-dependent, generic repository for data access
            /// </summary>
            /// <typeparam name="T">Type of entity for this Repository.</typeparam>
            public class EFRepository<T> : IRepository<T> where T : class
            {
                public EFRepository(DbContext dbContext)
                {
                    if (dbContext == null)
                        throw new ArgumentNullException("dbContext");
                    DbContext = dbContext;
                    DbSet = DbContext.Set<T>();

                }

                protected DbContext DbContext { get; set; }

                protected DbSet<T> DbSet { get; set; }


                public virtual IQueryable<T> GetAllLazyLoad(Expression<Func<T, bool>> filter, params Expression<Func<T, object>>[] children) 
                {


                        children.ToList().ForEach(x=>DbSet.Include(x).Load());
                        return DbSet;
                }

            }
        }
like image 34
hidden Avatar answered Oct 20 '22 02:10

hidden


Say goodbye to the hardcoded ObjectQuery(T).Include calls

If you're using EF > 4, then it's built in, check DbExtensions.Include on MSDN.

like image 5
Shimmy Weitzhandler Avatar answered Oct 20 '22 01:10

Shimmy Weitzhandler