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,通过该文的介 ...
随机推荐
- centos:添加用户
初步进入centos学习,配置用户 1,创建用户 创建用户 hadoop [root@master spark]# useradd hadoop [root@master spark]# 2,创建密码 ...
- GIT 如何从另一分支合并特定的文件
是否遇到过这种情景: 您在一个分支上工作,发现该分支上的某些文件实现的功能已经在其他分支上实现了 但因为这两个分支实现不同的功能,因此不能进行简单的合并工作,但您又不想重复其他已经完成的工作 以下操作 ...
- mysql 批量数据循环插入
双重循环插入 DELIMITER ;; CREATE PROCEDURE test_insert() BEGIN DECLARE a INT DEFAULT 1; DECLARE b TINYINT ...
- IIS 7启用static JSON文件能POST方法
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.we ...
- js escape 与php escape
javascript有编码函数escape()和对应的解码函数unescape(),而php中只有个urlencode和urldecode,这个编码和解码函数对encodeURI和encodeURIC ...
- 数据对接—kettle使用之四
上一篇介绍了表输出插件,并通过实例介绍插件的简单使用,如果有这样的需求大家可以参考一下并深入研究插件的其它细节设置.这一篇我们介绍和表输出对应的插件(表输入)的使用. 表输入: 1. 从步骤插入数据: ...
- 树莓派系统(Debain)中设置固定静态IP地址
一.方法: 1.使用ssh登陆,使用以下命令设置静态ip. sudo nano /etc/dhcpcd.conf2.在dhcpcd.conf后添加以下内容(网上的方法): interface eth0 ...
- WebRTC互联网实时通信
muaz-khan/WebRTC-Experiment WebRTC, WebRTC and WebRTC. Everything here is all about WebRTC!! Updated ...
- 如何处理Android中的防缓冲区溢出技术
[51CTO专稿]本文将具体介绍Android中的防缓冲区溢出技术的来龙去脉. 1.什么是ASLR? ASLR(Address space layout randomization)是一种针对缓冲区溢 ...
- tshark使用说明
tshark -h TShark (Wireshark) (v2.-gf42a0d2b6c) Dump and analyze network traffic. See https://www.wir ...