首先使用Entity框架代码实现Generic Repository [英] Implementing Generic Repository using Entity framework code first

查看:281
本文介绍了首先使用Entity框架代码实现Generic Repository的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了我的关于实施框架的通用仓库模式和单位的第一次尝试。我不是在手项目中使用MVC。
请看一看这个方法包括在通用仓库等级:

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,

推荐答案

要按照产品类别进行筛选,试试这个:

To filter by product category, try this:

var repo = new GenericRepository<Product>();

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

下面我们声明的通用信息库的一个实例,与产品的实体类型,然后我们通过一个LAMDA表达式执行每个产品的类别名称为富的过滤。

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".

这篇关于首先使用Entity框架代码实现Generic Repository的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆