Click here to Skip to main content
15,889,992 members
Articles / Web Development / ASP.NET

Introducing K-Pattern: A Rapid Way to Make CRUD Operations with Entity Framework

Rate me:
Please Sign up or sign in to vote.
4.74/5 (23 votes)
29 Jul 2014CPOL4 min read 35.8K   289   35   18
This article is all about of my developed entity framework pattern named “K-Pattern”

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.

Image 1

Image 2

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)


Written By
Software Developer (Senior)
India India
Eager to contribute highly applicable application development skills and ability to personalize service delivery to analyzing business needs and translating them into executable strategies.

Comments and Discussions

 
SuggestionMy vote 3 Pin
Mickey Perlstein6-Sep-14 1:04
Mickey Perlstein6-Sep-14 1:04 
Hey Kundan, (Liked your "K" slightly Megalomanian term, but cool.) Thumbs Up | :thumbsup:

First the pluses
1. You decided to face-off many issues you had with code copying.
2. You wrote a very eloquent article, very easy to read and follow. you are indeed a gifted trainer.
3. The way you responded bellow shows you have manners and are a "find goo in everything" kind of person
4. You saw something you didnt feel right with (or easy to use) and you decided to create your own - I AM PROUD. I really am. This one wasn't the best, but the next idea you have will be. YOU ARE AN ENTREPRENEUR, someone willing to try to CHANGE WHAT THEY GET FROM THE WORLD. I applaud you.

Now to some drawbacks in this endeavor
1. The EF runs over "tt" code generation templates that write all the crud operations for you.
2. EF and ORM in general are suppose to create two SRP types of objects: Agnostic entities that create an in-memory data model and a fully aware data-context repository able to persist and query data. You have mixed them into one. what's more, your Save algorithm (change the word pattern to algorithm please) goes against the whole concept of UnitOfWork concept.
3. Its hard to follow your API.
C#
objCourse.Students.AttachUs(Operation.Delete); 
requiring one to use a generic method with an enum for operation to delete is not a good API façade IMHO.
4. You're playing around with the internals of EF, attaching and detaching objects using its internal mechanism, making it hard for validations to take place.
5. You are using the old EntityObject hierarchy thereby removing agnosticy from entites (@see 2)
6. Your API requires you to attach the entity before adding child objects, this goes against the core of SRP as well as common sense IMO.

Beyong all this I will repeat myself.
Good work. Good try. You saw something you didn't like and you tried to change it! you should read code complete and watch S.O.L.I.D refactoring videos on youtube to add to you understanding and knowledge, but this just means you will create better and cooler things.

People who just say negatives are small insecure people. Don't listen to them. We Entrepreneurs fail 500 times and make it once. this is only that first failure.

I applaud you.
Mickey Perlstein

GeneralRe: My vote 3 Pin
Kundan Singh Chouhan15-Sep-14 7:50
Kundan Singh Chouhan15-Sep-14 7:50 
GeneralMy vote of 1 Pin
alec.whittington25-Aug-14 5:12
alec.whittington25-Aug-14 5:12 
GeneralRe: My vote of 1 Pin
Kundan Singh Chouhan25-Aug-14 6:14
Kundan Singh Chouhan25-Aug-14 6:14 
GeneralRe: My vote of 1 Pin
alec.whittington25-Aug-14 6:23
alec.whittington25-Aug-14 6:23 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA13-Aug-14 1:41
professionalȘtefan-Mihai MOGA13-Aug-14 1:41 
GeneralRe: My vote of 5 Pin
Kundan Singh Chouhan20-Aug-14 17:33
Kundan Singh Chouhan20-Aug-14 17:33 
Question[My vote of 1] This is normal Entity framework operation Pin
ptMujeeb31-Jul-14 1:38
professionalptMujeeb31-Jul-14 1:38 
AnswerRe: [My vote of 1] This is normal Entity framework operation Pin
Kundan Singh Chouhan31-Jul-14 17:43
Kundan Singh Chouhan31-Jul-14 17:43 
AnswerRe: [My vote of 1] This is normal Entity framework operation Pin
alec.whittington25-Aug-14 4:54
alec.whittington25-Aug-14 4:54 
GeneralRe: [My vote of 1] This is normal Entity framework operation Pin
Kundan Singh Chouhan25-Aug-14 6:09
Kundan Singh Chouhan25-Aug-14 6:09 
GeneralRe: [My vote of 1] This is normal Entity framework operation Pin
alec.whittington25-Aug-14 6:12
alec.whittington25-Aug-14 6:12 
GeneralRe: [My vote of 1] This is normal Entity framework operation Pin
Kundan Singh Chouhan27-Aug-14 7:09
Kundan Singh Chouhan27-Aug-14 7:09 
GeneralMy Vote 5 Pin
Sandeep Singh Shekhawat29-Jul-14 15:34
professionalSandeep Singh Shekhawat29-Jul-14 15:34 
GeneralRe: My Vote 5 Pin
Kundan Singh Chouhan29-Jul-14 17:18
Kundan Singh Chouhan29-Jul-14 17:18 
GeneralMy vote of 5 Pin
Volynsky Alex29-Jul-14 11:11
professionalVolynsky Alex29-Jul-14 11:11 
GeneralRe: My vote of 5 Pin
Kundan Singh Chouhan29-Jul-14 17:19
Kundan Singh Chouhan29-Jul-14 17:19 
GeneralRe: My vote of 5 Pin
Volynsky Alex30-Jul-14 10:06
professionalVolynsky Alex30-Jul-14 10:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.