Azarsa
Azarsa

Reputation: 1308

Repository Pattern get one entity and include properties

I use repository pattern and Entity Framework in C# with this generic methods:

public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

    public virtual TEntity GetByID(object id)
    {
        return dbSet.Find(id);
    }

Now I want write an overload for GetByID to accept includeproperties just like Get method that I have used. Something like this:

    public virtual TEntity GetByID(object id, string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;
        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }            
        return ???
    }

What should I return? Any suggestion?

Upvotes: 0

Views: 3039

Answers (1)

DanS
DanS

Reputation: 792

This is fairly dependent on your objects-- Do your entities implement a common interface that declares an ID property? In that scenario, you could query.SingleOrDefault(e => e.Id == id), however, in what seems the more likely scenario, you would need to either pass in a predicate to match or re-implement the Find() functionality.

In DBContext Find with Includes - where lambda with Primary keys, RBrowning99 pulled the entitiy keys from the context and matched based the first key:

public DALEntity Get(string ID, IEnumerable<string> IncludeEntities = null)
{
    var set = ((IObjectContextAdapter)context).ObjectContext.CreateObjectSet<DALEntity>();
    var entitySet = set.EntitySet;
    string[] keyNames = entitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();

    IQueryable<DALEntity> query = dbSet;
    query = IncludeEntities.Aggregate(query, (current, includePath) => current.Include(includePath));

    query = query.Where(keyNames[0] + "= @0", ID);
    return query.FirstOrDefault();
}

Upvotes: 2

Related Questions