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,通过该文的介 ...
随机推荐
- sonarqube 5.6
转载:https://www.jianshu.com/p/402987500bfd 一. 简介 Sonar是一个用于代码质量管理的开源平台,用于管理源代码的质量.通过插件形式,可以支持包括java,C ...
- HotSpot Java虚拟机中的“方法区”“持久代”“元数据区”的关系?
Sun/Oracle JDK的HotSpot VM中,直到JDK7都有“持久代”(Permanent Generation,简称PermGen).也称为方法区.Oracle JDK8的HotSpot ...
- 浅谈压缩感知(六):TVAL3
这一节主要介绍一下压缩感知中的一种基于全变分正则化的重建算法——TVAL3. 主要内容: TVAL3概要 压缩感知方法 TVAL3算法 快速哈达玛变换 实验结果 总结 1.TVAL3概要 全称: To ...
- WIN10系统如何隐藏底部搜索框
右击任务栏,搜索,可以切换三种模式,建议还是显示搜索图标,因为这个搜索还是能比较快速定位到系统功能的,只不过显示搜索框的话比较占地方,不方便
- 微信小程序 - 支持html空格(提示)
仅限于text标签,decode参数:官方api.
- Java 代码行统计(转)
package codecounter; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFound ...
- CSS拾遗
1:CSS样式的声明 选择符{ 属性:值; 属性:值; ... } 其中,选择符有: 标签选择器:标签名{样式} 类选择器: .类名{样式} ID选择器: #ID名{样式} 另外:样式属性的书写格式 ...
- Cocos2d 编译js为jsc bytecode文件
使用: cocos jscompile -s XXX(目录名,会递归) -d (输出的目录) 但编译后的jsc比原来的js更大了 如果只是为了代码的保密性,也许只需要用yuicompres ...
- 阿里历年经典Java面试题汇总,想进BAT你还不快收藏!
转载:https://mp.weixin.qq.com/s/M8YyxloxZnMACH9QCQN7HA Volatile的特征: A.禁止指令重排(有例外) B.可见性 Volatile的内存语义: ...
- Netstat命令详解(windows下)
Netstat 用于显示与IP .TCP .UDP 和ICMP 协议相关的统计数据,一般用于检验本机各端口的网络连接情况. 如果你的计算机有时候接收到的数据报导致出错数据或故障,你不必感到奇怪,T ...