Implementing Generic Repository using Entity framework code first

若如初见. 提交于 2019-12-10 19:33:48

问题


I'm experiencing my first try on implementing Generic Repository Pattern and Unit of framework. I'm not using MVC on the project in hand. Please take a look at this method included in Generic Repository class:

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();
        }
    }

it must be a powerful method and accomplishes the goal of DRY well. My problem is that, I cannot order the result as descending? Can anyone write some lines of code to help me on this? Thanks,


回答1:


To filter by product category, try this:

var repo = new GenericRepository<Product>();

var results = repo.Get(
    p => p.Category.Name == "Foo");

Here we declare an instance of the Generic Repository, with an entity type of Product, then we pass a lamda expression that performs the filtering on each Product's Category whose name is "Foo".




回答2:


Have a look at this: http://prodinner.codeplex.com/ and this http://efmvc.codeplex.com/. These projects are good examples of simple architecture and you can see how generic repository is implemented and how it is used.



来源:https://stackoverflow.com/questions/16611031/implementing-generic-repository-using-entity-framework-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!