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 AddedModified and Deleted. New extension methods have been defined for three classes EntityObjectEntityCollection<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

 Collapse | Copy Code
Course objCourse = new Course
{
Name = "B.Sc.",
Duration = "3 Years"
}; objCourse.Save();

Insert Parent & Insert Children

 Collapse | Copy Code
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

 Collapse | Copy Code
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

 Collapse | Copy Code
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

 Collapse | Copy Code
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

 Collapse | Copy Code
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的更多相关文章

  1. 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 ...

  2. [转]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 ...

  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 Repository Pattern in Entity Framework

    One of the most common pattern is followed in the world of Entity Framework is “Repository Pattern”. ...

  5. 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 ...

  6. 5.在MVC中使用泛型仓储模式和工作单元来进行增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

  7. 在MVC中使用泛型仓储模式和工作单元来进行增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

  8. 6.在MVC中使用泛型仓储模式和依赖注入实现增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

  9. 1.【使用EF Code-First方式和Fluent API来探讨EF中的关系】

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/relationship-in-entity-framework-using-code-firs ...

随机推荐

  1. 让maven生成可运行jar包

    平时项目大多用到的是war包,今天实现了一个简单功能,无需部署到web服务器上,只需本地跑java代码即可,因此只要生成一个jar包.那么怎么让maven项目打成一个可以使用java命令跑的jar包呢 ...

  2. 通过docker构建zabbix监控系统

    下载zabbix的镜像 $ docker pull berngp/docker-zabbix Using default tag: latest latest: Pulling from berngp ...

  3. javascript中原型学习

    学习地址:http://www.cnblogs.com/wangfupeng1988/tag/%E5%8E%9F%E5%9E%8B/

  4. 【brew使用技巧】fix links

    brew link --overwrite python

  5. 【转】 Pro Android学习笔记(九五):AsyncTask(4):执行情况

    目录(?)[-] 两个AsyncTask对象的运行情况 多次执行的异常 文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog.csdn.net/ ...

  6. (转) Docker - Docker1.12服务发现,负载均衡和Routing Mesh

    看到一篇介绍 Docker swarm以及如何编排的好文章,挪放到这里,自己学习的同时也分享出来. 原文链接: http://wwwbuild.net/dockerone/414200.html -- ...

  7. 命令提示符(cmd)中的tracert命令详解(小技巧)

    tracert也被称为Windows路由跟踪实用程序,在命令提示符(cmd)中使用tracert命令可以用于确定IP数据包访问目标时所选择的路径.本文主要探讨了tracert命令的各个功能. 百度经验 ...

  8. HDFS案例

    shell日志采集 需求说明 点击流日志每天都10T,在业务应用服务器上,需要准实时上传至数据仓库(Hadoop HDFS)上 需求分析 一般上传文件都是在凌晨24点操作,由于很多种类的业务数据都要在 ...

  9. 用eclipse+svn插件,上传新项目到svn服务器

    给定trunk路径,https://svn.ws.125089.com/public/nlp/3434index/IndexByModelSolr/trunk/. 其中自己的web项目名字是Index ...

  10. 【bzoj1614】[Usaco2007 Jan]Telephone Lines架设电话线

    题目描述 Farmer John打算将电话线引到自己的农场,但电信公司并不打算为他提供免费服务.于是,FJ必须为此向电信公司支付一定的费用.     FJ的农场周围分布着N(1 <= N < ...