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. iredmail安装问题

    =================================== 已解决::::(据铭哥说 只有最新版0.9.2才会出现这个问题) 解决办法::(都是IPv6惹的祸) vi /etc/dovec ...

  2. Solidworks如何替换工程图参考零件

    不要在左侧树形图右击修改   而是要在右侧主视图上右击,替换模型   左侧浏览找到新的零件,然后打开   替换完成之后,会有一些尺寸变成黄色,只需要改动黄色部分即可,不需要每个尺寸重新标注    

  3. Discuz常见小问题-如何取消帖子置顶

    定位到一个帖子,然后顶部会有置顶的选项,还是勾选置顶,后面下拉列表选择无,然后点击确定,提示解除置顶  

  4. CSS 之 div中文字超出时自动换行

          在开发中很容易遇到div中文字超出的问题,在此总结以下方法: 1. white-space :属性设置如何处理元素内的空白.这个属性声明建立布局过程中如何处理元素中的空白符.所有浏览器都支 ...

  5. SHELL字符串使用总结

    1.获取字符串的长度,${#str} #设置字符串 $ str="liqiu" #打印字符串 $ echo $str liqiu #继续打印字符串 $ echo ${str} li ...

  6. angularjs也支持script形式的template

    <script type="text/ng-template" id="name"> https://docs.angularjs.org/api/ ...

  7. Kafka 跨集群同步方案(转)

    来自:http://tangzhaohui.net/524 Kafka 跨集群同步方案——Kafka内置的MirrorMaker工具 该方案解决Kafka跨集群同步.创建Kafka集群镜像等相关问题, ...

  8. infobright系列三:数据导入乱码

    1:目前在用的是社区版的infobright,不支持DML功能,只能用LOAD DATA方式导入数据. 如果元数据中有特殊控制字符,导入过程中经常会报错 2: 设置Reject File导入之前,设定 ...

  9. ReactNative踩坑日志——页面跳转之——Undefined is not an Object(evaluating this2.props.navigation.navigate)

    页面跳转时,报  Undefined is not an Object(evaluating this2.props.navigation.navigate) 出错原因:在一个页面组件中调用了另一个组 ...

  10. Linux(centos)新建,删除,移动,重命名文件夹和文件的命令

    1.新建文件夹 mkdir 文件名 新建一个名为test的文件夹在home下 view source1 mkdir /home/test 2.新建文本 在home下新建一个test.sh脚本 vi / ...