One of the most common pattern is followed in the world of Entity Framework is “Repository Pattern”. Since this is something which is heavily used and being practiced, I am not going to talk about the core pattern. Rather, try to show how one can implement it.

Objectives

As mentioned in http://msdn.microsoft.com/en-us/library/ff649690.aspx

  • You want to maximize the amount of code that can be tested with automation and to isolate the data layer to support unit testing.
  • You access the data source from many locations and want to apply centrally managed, consistent access rules and logic.
  • You want to implement and centralize a caching strategy for the data source.
  • You want to improve the code’s maintainability and readability by separating business logic from data or service access logic.
  • You want to use business entities that are strongly typed so that you can identify problems at compile time instead of at run time.
  • You want to associate a behavior with the related data. For example, you want to calculate fields or enforce complex relationships or business rules between the data elements within an entity.
  • You want to apply a domain model to simplify complex business logic.

Simple approach to ADO.NET Entity Framework

Let’s have one domain class called “Employee”

public class Employee
{
    public int Id { get; set; }
    public string FullName { get; set; }
}
 
Now using this we will have a simple context class
public class HRContext : DbContext
{
    public DbSet<DomainClasses.Employee> Employees { get; set; }
}
After that, define the repository interface IEmployeeRepository
 
public interface IEmployeeRepository : IDisposable
{
    IQueryable<Employee> All { get; }
    IQueryable<Employee> AllIncluding(params Expression<Func<Employee, object>>[] includeProperties);
    Employee Find(int id);
    void InsertOrUpdate(Employee employee);
    void Delete(int id);
    void Save();
}

Then the Repository class called EmployeeRepository

 
public class EmployeeRepository : IEmployeeRepository
{
    HRContext context = new HRContext();

    public IQueryable<Employee> All
    {
        get { return context.Employees; }
    }

    public IQueryable<Employee> AllIncluding(params Expression<Func<Employee, object>>[] includeProperties)
    {
        IQueryable<Employee> query = context.Employees;
        foreach (var includeProperty in includeProperties) {
            query = query.Include(includeProperty);
        }
        return query;
    }

    public Employee Find(int id)
    {
        return context.Employees.Find(id);
    }

    public void InsertOrUpdate(Employee employee)
    {
        if (employee.Id == default(int)) {
            // New entity
            context.Employees.Add(employee);
        } else {
            // Existing entity
            context.Entry(employee).State = EntityState.Modified;
        }
    }

    public void Delete(int id)
    {
        var employee = context.Employees.Find(id);
        context.Employees.Remove(employee);
    }

    public void Save()
    {
        context.SaveChanges();
    }

    public void Dispose()
    {
        context.Dispose();
    }
}
 
Then you should be implementing it in your apps (any type Windows or Web), like a Console Application
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            GetSomeEmployee();
        }

        private static void IntiateData()
        {
            using (var repo = new EmployeeRepository())
            {
                Employee em = new Employee() { FullName = "Wriju" };
                repo.InsertOrUpdate(em);
                repo.Save();
            }
        }

        private static void GetSomeEmployee()
        {
            using (var repo = new EmployeeRepository())
            {
                foreach (var emp in repo.All)
                {
                    Console.WriteLine("{0} - {1}", emp.Id, emp.FullName);
                }
            }
        }
    }
}
 
This obviously simple approach. The recommended options are to make the Repository generic and handle the related entities. I will discuss about them later.
 
Namoskar!!!

Using Repository Pattern in Entity Framework的更多相关文章

  1. [转]Upgrading to Async with Entity Framework, MVC, OData AsyncEntitySetController, Kendo UI, Glimpse & Generic Unit of Work Repository Framework v2.0

    本文转自:http://www.tuicool.com/articles/BBVr6z Thanks to everyone for allowing us to give back to the . ...

  2. [转]Entity Framework and SQL Azure

    本文转自:https://msdn.microsoft.com/zh-cn/library/gg190738 Julie Lerman http://thedatafarm.com April 201 ...

  3. Generic repository pattern and Unit of work with Entity framework

    原文 Generic repository pattern and Unit of work with Entity framework Repository pattern is an abstra ...

  4. Using the Repository Pattern with ASP.NET MVC and Entity Framework

    原文:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-and ...

  5. [转]Using the Repository Pattern with ASP.NET MVC and Entity Framework

    本文转自:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-a ...

  6. 分享基于Entity Framework的Repository模式设计(附源码)

    关于Repository模式,在这篇文章中有介绍,Entity Framework返回IEnumerable还是IQueryable? 这篇文章介绍的是使用Entity Framework实现的Rep ...

  7. Entity Framework Repository模式

    Repository模式之前 如果我们用最原始的EF进行设计对每个实体类的“C(增加).R(读取).U(修改).D(删除)”这四个操作. 第一个:先来看看查询,对于实体类简单的查询操作,每次都是这样的 ...

  8. 在Entity Framework 4.0中使用 Repository 和 Unit of Work 模式

    [原文地址]Using Repository and Unit of Work patterns with Entity Framework 4.0 [原文发表日期] 16 June 09 04:08 ...

  9. 在Apworks数据服务中使用基于Entity Framework Core的仓储(Repository)实现

    <在ASP.NET Core中使用Apworks快速开发数据服务>一文中,我介绍了如何使用Apworks框架的数据服务来快速构建用于查询和管理数据模型的RESTful API,通过该文的介 ...

随机推荐

  1. Kafka:ZK+Kafka+Spark Streaming集群环境搭建(七)针对hadoop2.9.0启动DataManager失败问题

    DataManager启动失败 启动过程中发现一个问题:slave1,slave2,slave3都是只启动了DataNode,而DataManager并没有启动: [spark@slave1 hado ...

  2. 7.4 Javascript:表单验证-揭开正則表達式的面纱

    用元字符匹配对应的字符类型 创建正則表達式有点像创建字符串字面量,仅仅只是正則表達式出如今一对"/"里 正則表達式中会用到一级元字符.用于连接字母与数字 "." ...

  3. OpenWRT使用wifidog实现强制认证的WIFI热点

    首先安装wifidog到OpenWRT的路由器: opkg update opkg install wifidog wifidog依赖下面这些模块: iptables-mod-extra iptabl ...

  4. 查看oracle的sql语句历史记录和锁表的情况

    查看oracle的sql语句历史记录和锁表的情况 (2012-01-04 20:59:59) 转载▼ 标签: 杂谈 分类: database 查询sql的历史记录 select * from v$sq ...

  5. asp.net 常用于客户端注册的机器信息

    项目需要:根据客户端信息去获取用户登录信息 1.根据客户端信息,并查询数据库是否有匹配.如果没有则重新插入客户端信息: 2.根据客户端的设置提交用户登录信息,用户登录成功后,查询以前是否有过配置信息, ...

  6. angularJS 事件广播与接收[转]

    路由的事件 事件这个词在前端出现的频率真是高,根本拦不住,哪都是.$route服务在路由过程中的每个阶段都会触发不同的事件,可以为这些不同的路由事件设置监听器并做出响应. 一共有4个事件用来监听路由的 ...

  7. linux2.6.30.4内核移植(5)——构建根文件系统(yaffs文件系统格式的镜像)

    一.首先编译并安装BusyBox 这里使用的交叉编译器还是3.4.5. 注意:编译内核.编译BusyBox以及编译文件系统中的所有应用程序的交叉编译器要使用同一个版本. 1.获取BusyBox源码 下 ...

  8. python 爬虫资料

    API Requests PyQuery http://www.tuicool.com/articles/UZrmUb2 http://blog.csdn.net/cnmilan/article/de ...

  9. cmder切换路径、设置命令别名

    alias alias hub= cd /d d:github/ cd $ help cd 显示当前目录名或改变当前目录. CHDIR [/D] [drive:][path] CHDIR [..] C ...

  10. Hibernate4获得Session

    在Hibernate3中获取Session的方法: Session session = this.getSession(): 前提是类要继承HibernateDaoSupport: public cl ...