Using Repository Pattern in Entity Framework
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; }
}
public class HRContext : DbContext
{
public DbSet<DomainClasses.Employee> Employees { get; set; }
}
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();
}
}
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);
}
}
}
}
}
Using Repository Pattern in Entity Framework的更多相关文章
- [转]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 . ...
- [转]Entity Framework and SQL Azure
本文转自:https://msdn.microsoft.com/zh-cn/library/gg190738 Julie Lerman http://thedatafarm.com April 201 ...
- 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 ...
- 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 ...
- [转]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 ...
- 分享基于Entity Framework的Repository模式设计(附源码)
关于Repository模式,在这篇文章中有介绍,Entity Framework返回IEnumerable还是IQueryable? 这篇文章介绍的是使用Entity Framework实现的Rep ...
- Entity Framework Repository模式
Repository模式之前 如果我们用最原始的EF进行设计对每个实体类的“C(增加).R(读取).U(修改).D(删除)”这四个操作. 第一个:先来看看查询,对于实体类简单的查询操作,每次都是这样的 ...
- 在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 ...
- 在Apworks数据服务中使用基于Entity Framework Core的仓储(Repository)实现
<在ASP.NET Core中使用Apworks快速开发数据服务>一文中,我介绍了如何使用Apworks框架的数据服务来快速构建用于查询和管理数据模型的RESTful API,通过该文的介 ...
随机推荐
- 【Python】由host得到IP
代码: import socket host='www.163.com' ip=socket.gethostbyname(host) print('Ip of {} is {}'.format(hos ...
- 【Python】使用torrentParser1.03对单文件torrent的分析结果
C:\Users\horn1\Desktop\python\42-torrentParser>python torrentParser.py 文件名=./5.torrent 文件结构: anno ...
- 【Python】使用torrentParser1.02对单文件torrent的分析结果
C:\Users\horn1\Desktop\python\41-torrentParser>python torrentParser.py 文件名=./5.torrent 文件结构: anno ...
- LintCode: Maximum Subarray
1. 暴力枚举 2. “聪明”枚举 3. 分治法 分:两个基本等长的子数组,分别求解T(n/2) 合:跨中心点的最大子数组合(枚举)O(n) 时间复杂度:O(n*logn) class Solutio ...
- HTML页面跳转的5种方式
下面列了五个例子来详细说明,这几个例子的主要功能是:在5秒后,自动跳转到同目录下的hello.html(根据自己需要自行修改)文件. 1) html的实现 <head> <!-- 以 ...
- 从MyEclipse到IntelliJ IDEA ——让你脱键盘,全键盘操作
从MyEclipse到IntelliJ IDEA ——让你脱键盘,全键盘操作 从MyEclipse转战到IntelliJ IDEA的经历 我一个朋友写了一篇“从Eclipse到Android Stud ...
- linux2.6.30.4内核移植(7)——插入hello world驱动模块
详细步骤参考自:http://www.cnblogs.com/wanyao/archive/2011/11/21/2257628.html 过程比较顺利,结果截图如下: 这里需要注意的是:http:/ ...
- Linux内核配置.config文件
在命令行中,进入顶层内核目录,并输入命令make menuconfig,就可以启动一个基于菜单的内核配置编辑器.从这里开始,你可以访问每个可用的配置参数,并生成一个定制的内核配置. 当你退出配置编辑器 ...
- QT 截取屏幕的实现
QPixmap提供了两个函数 grabWidget 和 grabWindow 可以将屏幕上的窗体存成一个 QPixmap 格式的图片,很容易再将 QPixmap 存成文件.函数使用很简单,两行代码就可 ...
- iOS开发 - Core Animation 核心动画
Core Animation Core Animation.中文翻译为核心动画,它是一组很强大的动画处理API,使用它能做出很炫丽的动画效果.并且往往是事半功倍. 也就是说,使用少量的代码就能够实现很 ...