ntroducing K-Pattern: A Rapid Way to Make CRUD Operations with Entity Framework
Introduction
Earlier in the last year I made a different approach to work on Entity Framework and in that I made some classes to handle the ObjectContext
in single request scope and some extension methods to handle Insert / Update / Delete for all the edmx designer classes. Using that way I realized that how fast we can make applications with it but there are some things which are missing on that way. I worked on those drawbacks and now it’s in front of you.
This article is a remake of my earlier Article/Tip "Best way to use Entity Framework". I’ll describe new features and methods of “Helper.cs”
class and will also compare this approach with some other approaches in the market in this article.
Background
Please go through the Part 1 before reading this article to understand the “Global Context” and “Helper” classes. After writing the 1st part, Debates were done among the developers that are is this the “Best way to use Entity Framework”? So to make it more understand it is best because of below things:
- DataContext alive and disposes on
HttpContext
basis so you do not need to write the code for initialize and dispose again and again in code blocks. - The Insert, Delete and Update methods are attached with Data Context Entity classes without any change effect in the original designer file. So developer does not need to write individual functions for these operations for each entity class.
- Single Method for Insert and Update.
- Easy and Fast to implement
However, there are some other patterns that also follow the same rule but there are lot of code involves to making it happen.
What's New?
The previous “Helper.cs” doesn’t allow Insert/Update/Delete operations on relational entities therefore It only works on Single Entity. This was the major drawback but now I have added some new methods to get overcome this issue. There is a new enum Operation
introduce to define EntitySet Operations like Added
, Modified
and Deleted
. New extension methods have been defined for three classes EntityObject, EntityCollection<T> and ObjectContext. The list of methods with their classes and signatures are mentioned below:
Class | Methods | Description |
EntityObject |
AttachMe(this EntityObject objEntity) | Attach the current entity object with defined Global Context in Global.cs. |
AttachMe(this EntityObject objEntity, Operation oper) | Attach the current entity object with defined Global Context in Global.cs and Change its state according to the provided Operation enum | |
DetachMe(this EntityObject entity) | Detach the current entity object with defined Global Context in Global.cs | |
EntityCollection<T> |
AttachUs<T>(this EntityCollection<T> entities, Operation oper) where T : EntityObject | Generic method to attach the whole collection with define Global Context in Global.cs |
DetachUs<T>(this EntityCollection<T> entities) where T : EntityObject | Generic method to attach the whole collection with define Global Context in Global.cs | |
ObjectContext |
AttachObject(this ObjectContext context, EntityObject objEntity) | Attach the provided entity with provided context. |
AttachObject(this ObjectContext context, EntityObject objEntity, Operation oper) | Attach the provided entity with provided context and change its state according the provided operation. | |
DetachObject(this ObjectContext Context, EntityObject entity) | Detach the provided entity with provided context. |
Let's Get Started
To demonstrate the new methods, we are going to make a DB (db_EntityFrameworkSample)
and create two tables which have One to Many Relationship
between.
In above diagram there are two tables Course
and Student
and they are associated via One to Many Relationship
. We are going to perform operations on these tables in following order.
Single Entity Operations

Course objCourse = new Course
{
Name = "B.Sc.",
Duration = "3 Years"
}; objCourse.Save();
Insert Parent & Insert Children

Course objCourse = new Course
{
Name = "M.Sc.",
Duration = "3 Years"
}; objCourse.AttachMe(); // Here we attached the current object with entity object context to perform operations on children entities objCourse.Students.Add(new Student { Name = "John", FName = "David" });
objCourse.Students.Add(new Student { Name = "Bob", FName = "Jason" }); objCourse.Save();
Update Parent & Insert Children

Course objCourse = Course.GetCourse(2); // Get MCA Cource objCourse.Students.Add(new Student { Name = "Niroo", FName = "Rob" });
objCourse.Students.Add(new Student { Name = "Chirs", FName = "William" }); objCourse.Save();
Update Parent & Update Children

Course objCourse = Course.GetCourse(2); // Get MCA Course objCourse.Students.ElementAtOrDefault(0).BirthDate = new DateTime(1986, 12, 15);
objCourse.Students.ElementAtOrDefault(1).BirthDate = new DateTime(1990, 7, 15); objCourse.Save();
Update Parent & Delete Children

Course objCourse = Course.GetCourse(4); // Get M-Tech Course objCourse.Duration = "4 Years";
objCourse.Students.AttachUs(Operation.Delete); // Attach student with context and change the EntityState to Deleted objCourse.Save();
Delete Parent & Delete Children

Course objCourse = Course.GetCourse(3); // Get B-Tech Course objCourse.Students.AttachUs(Operation.Delete); // Attach student with context and change the EntityState to Deleted objCourse.Delete();
Above are sample codes which define the data operations between Parent-Child entities with different combinations using "K-Pattern".
Comparision With Repository Pattern
Feature | K-Pattern | Repository Pattern |
Easy to implement | YES | NO |
Context Scope in Single Request | YES | YES (With IOC) |
Suitable Project Types | Small and Medium Types | Large Type |
Support for EF Approaches | Database First | Code First and Database First |
Conclusion
This is all about the K-Pattern. Thre are lot of discussion coming along with this approach and I'll be waiting for your reviews and suggestions to improve it better. Please downaload the source code, create the DB with the available SQL Script, chagne the conenction string and run it straight.
Thanks for reading. Happy coding.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
ntroducing K-Pattern: A Rapid Way to Make CRUD Operations with Entity Framework的更多相关文章
- 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 ...
- 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 Repository Pattern in Entity Framework
One of the most common pattern is followed in the world of Entity Framework is “Repository Pattern”. ...
- IMPLEMENTATION - Entity Framework Anti Pattern - High Performance EF
Good about ORM Developer is free from building T-Sql on the database tier which is not their major a ...
- 5.在MVC中使用泛型仓储模式和工作单元来进行增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...
- 在MVC中使用泛型仓储模式和工作单元来进行增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...
- 6.在MVC中使用泛型仓储模式和依赖注入实现增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...
- 1.【使用EF Code-First方式和Fluent API来探讨EF中的关系】
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/relationship-in-entity-framework-using-code-firs ...
随机推荐
- android通过查询电话号码获取联系人信息
// 取得Intent中的頭像 ivShowImage = (ImageView) findViewById(R.id.call_log_detail_contact_img); //通话电话号码获取 ...
- Ubuntu15.10下Hadoop2.6.0伪分布式环境安装配置及Hadoop Streaming的体验
Ubuntu用的是Ubuntu15.10Beta2版本,正式的版本好像要到这个月的22号才发布.参考的资料主要是http://www.powerxing.com/install-hadoop-clus ...
- sqldeveloper和plsqldebeloper
sqldeveloper : 支持不用tns连,支持jdbc直接连的. plsqldebeloper : 必须使用tns连, 如果oracle安装在本机,本机已经有tns文件,和oci.dll,只需在 ...
- FPGA中的“门”
逻辑门 在ASIC的世界里,衡量器件容量的常用标准是等效门.这是因为不同的厂商在单元库里提供了不同的功能模块,而每个功能模块的实现都要求不同数量的晶体管.这样在两个器件之间比较容量和复杂度就很困难. ...
- 【转】Jenkins+Ant+Jmeter搭建持续集成的接口测试平台
一.什么是接口测试? 接口测试是测试系统组件间接口的一种测试.接口测试主要用于检测外部系统与系统之间以及内部各个子系统之间的交互点.测试的重点是要检查数据的交换,传递和控制管理过程,以及系统间的相互逻 ...
- Spring Batch介绍
简介 SpringBatch 是一个大数据量的并行处理框架.通常用于数据的离线迁移,和数据处理,⽀持事务.并发.流程.监控.纵向和横向扩展,提供统⼀的接⼝管理和任务管理;SpringBatch是Spr ...
- 谷歌浏览器无法播放QQ空间视频动画的解决方案
https://qzonestyle.gtimg.cn/qzone/photo/v7/js/module/flashDetector/flash_tutorial.pdf Chrome开启⽅法 1. ...
- 微信小程序之如何使用iconfont
如何在小程序中使用iconfont 1.添加入库 2.加入项目 3.下载ttf 4.进行base64处理,在这个平台https://transfonter.org/ 上转换一下格式为base64位. ...
- dd命令的高级应用
dd是Linux上的一个常用的命令.例如:dd if=/1.txt of=/tmp/2.txt (其中, if代表input file:of代表output file, 命令的结果就是将根目录 ...
- java成神之——集合框架之队列,栈,集合并发
集合 队列和双端队列 PriorityQueue Deque BlockingQueue Queue 栈 集合并发 线程锁 线程安全集合 结语 集合 队列和双端队列 PriorityQueue 此队列 ...