Repository Pattern and Unit of Work with Entity Framework

Similar documents
MVC - Repository-And-Unit-Of-Work

LAMPIRAN. 1. Source Code Data Buku. using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.

.NET Database Technologies. Entity Framework: Queries and Transactions

MSSQL and.net. Using SQL in.net, running.net code in SQL Server

Item 18: Implement the Standard Dispose Pattern

Error! Bookmark not defined.

DATABASES SQL INFOTEK SOLUTIONS TEAM

C # 7, 8, and beyond: language features from design to release to IDE support. Kevin

Objectives. Introduce static keyword examine syntax describe common uses

Entity Framework. #entityframework

Rx is a library for composing asynchronous and event-based programs using observable collections.

Representing Recursive Relationships Using REP++ TreeView

The Data Access Layer:

CS159. Nathan Sprague. September 30, 2015

Reflection in C# Case studies in metaprogramming. torsdag 6 mars 14

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Chapter 15: How to Work with Interfaces and Generics

Applied NoSQL in.net

HIBERNATE MOCK TEST HIBERNATE MOCK TEST IV

Introduction to C# Applications

Semantic & Immutable Types

How to be a C# ninja in 10 easy steps. Benjamin Day

BST Implementation. Data Structures. Lecture 4 Binary search trees (BST) Dr. Mahmoud Attia Sakr University of Ain Shams

Grading Rubric Homework 1

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Adapting a Grid to REP++

Developing Mobile Apps with Xamarin and Azure

Effective C# Presentation By: Brian Braatz. Derived from the book Effective C# 2 nd Edition

FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING

What property of a C# array indicates its allocated size? What keyword in the base class allows a method to be polymorphic?

COE318 Lecture Notes Week 10 (Nov 7, 2011)

IDIOM + BUSINESS RULES BEANS

C# COMO VOCÊ (TALVEZ) NUNCA VIU

C# s A Doddle. Steve Love. ACCU April 2013

Test Isolation and Mocking

Previous C# Releases. C# 3.0 Language Features. C# 3.0 Features. C# 3.0 Orcas. Local Variables. Language Integrated Query 3/23/2007

How to transfer data between BPMonline 7.x environments

Java Persistence API (JPA) Entities

5/2/2017. The entity manager. The entity manager. Entities lifecycle and manipulation

inside: THE MAGAZINE OF USENIX & SAGE August 2003 volume 28 number 4 PROGRAMMING McCluskey: Working with C# Classes

MICRO SERVICES ARCHITECTURE

TARGETPROCESS PLUGIN DEVELOPMENT GUIDE

Exercise Session Week 9 GC and Managed Memory Leaks

Saikat Banerjee Page 1

Declarations and Access Control SCJP tips

Chapter 12: How to Create and Use Classes

Type Conversion. and. Statements

EL-USB-RT API Guide V1.0

Transaction Isolation Level in ODI

Introduction. Example Databases

Q&As. Microsoft MTA Software Development Fundamentals. Pass Microsoft Exam with 100% Guarantee

Lesson learned from using EMF to build Desktop & Web Applications. Ludwigsburg, Oct

ADF Mobile Code Corner

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

SQL Server Containers for Developers. Julie Lerman

Vive Input Utility Developer Guide

Introduction to Programming Using Java (98-388)

Spring Professional v5.0 Exam

Outline. Logistics. Logistics. Principles of Software (CSCI 2600) Spring Logistics csci2600/

Equality in.net. Gregory Adam 07/12/2008. This article describes how equality works in.net

SQLite Database. References. Overview. Structured Databases

Working with Databases and Java

PASS4TEST IT 인증시험덤프전문사이트

C#: framework overview and in-the-small features

MCSA Universal Windows Platform. A Success Guide to Prepare- Programming in C# edusum.com

Array. Prepared By - Rifat Shahriyar

Introduce C# as Object Oriented programming language. Explain, tokens,

How NikeiD Hurdled the Java Technology and Flash Barrier

Creating a Transacted Resource Using System.Transactions (Lab 2) (Visual C#, Visual Basic)

A Guide to a Dedicated Event Graph Simulator for a Single Server System. October, 2013 Byoung K. Choi and Donghun Kang

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

Object-Oriented Programming Concepts

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

User Plugins. About Plugins. Deploying Plugins

Domain Driven Design, MVC & Entity Framework

Mobile and Ubiquitous Computing: Android Programming (part 4)

Q&As. Transition Your MCITP: Database Administrator 2008 or MCITP: Database Developer 2008 to MCSE: Data Platform

Object Oriented Programming

The Basis of Data. Steven R. Bagley

CS350: Data Structures Stacks

1d: tests knowing about bitwise fields and union/struct differences.

C# machine model. Programming Language Concepts and Implementation Fall 2011, Lecture 2. Rasmus Ejlers Møgelberg

.NET Three Examples of Applied Patterns Jimmy Nilsson

RDBMS Transaction Isolation Levels

Android Data Binding: This is the DSL you're looking for

Database Management System

Homework 1 Due September 26th, 11:59pm ET

Transactional Web Feature Server Design

Database Foundations. 1-2 Introduction to Databases. Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Domain-Driven Design Activity

Lampiran. SetoransController

An abstract tree stores data that is hierarchically ordered. Operations that may be performed on an abstract tree include:

1 Copyright 2011, Oracle and/or its affiliates. All rights reserved.

Linked List. ape hen dog cat fox. tail. head. count 5

1 Copyright 2011, Oracle and/or its affiliates. All rights reserved.

Sql Server Syllabus. Overview

A Long Time Ago 2 / 64

Alfresco repo under concurrent write load. Alexey Vasyukov, ITD Systems

Oracle Berkeley DB XML. API Reference for C++ 12c Release 1

Learn Well Technocraft

Transcription:

Repository Pattern and Unit of Work with Entity Framework Repository pattern is used to create an abstraction layer between the data access layer and the business logic layer. This abstraction layer contains data manipulation methods which communicate with the data access layer to serve data as per the business requirements to the logical layer. The main purpose to create this layer is for isolating data access layer so that changes cannot affect the business logic layer directly. For example, a POS application is usually deployed to different stores. A few new clients wanted to use the Microsoft SQL Server database system and some others wanted Oracle and other databases. Also they had a few different relational database systems to store their data but business logic was almost the same. Repository pattern helps developers to detach the layer and add a new data access layer. Unit of work is a pattern to handle transaction during data manipulation using the Repository pattern. So we can say, according to Martin Fowler, Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problem. Implementing these patterns can help insulate the application from changes in the data store and also gives advantages to automate unit testing.

A database for the application with the following tables:

Contact.Repository class as well as its required interfaces. Fig: Interface and class diagram given for EntityFramework Repository public interface IBaseRepository<T> T Single(object primarykey); T SingleOrDefault(object primarykey); IEnumerable<T> GetAll(); bool Exists(object primarykey); int Insert(T entity);

void Update(T entity); public interface IUnitOfWork : IDisposable /// <summary> /// Call this to commit the unit of work /// </summary> void Commit(); /// <summary> /// Return the database reference for this UOW /// </summary> DbContext Db get; /// <summary> /// Starts a transaction on this unit of work /// </summary> void StartTransaction(); public class UnitOfWork : IUnitOfWork private TransactionScope _transaction; private readonly ContactDBEntities _db; public UnitOfWork() _db = new ContactDBEntities(); public void Dispose()

public void StartTransaction() _transaction = new Transaction Scope(); public void Commit() _db.savechanges(); _transaction.complete(); public DbContext Db get return _db; public class BaseRepository<T> : IBaseRepository<T> where T : class private readonly IUnitOfWork _unitofwork; internal DbSet<T> dbset; public BaseRepository(IUnitOfWork unitofwork) if (unitofwork == null) throw new ArgumentNullException("unitOfWork"); _unitofwork = unitofwork; this.dbset = _unitofwork.db.set<t>();

/// <summary> /// Returns the object with the primary key specifies or throws /// </summary> /// <typeparam name="tu">the type to map the result to</typeparam> /// <param name="primarykey">the primary key</param> /// <returns>the result mapped to the specified type</returns> public T Single(object primarykey) var dbresult = dbset.find(primarykey); return dbresult; public T SingleOrDefault(object primarykey) var dbresult = dbset.find(primarykey); return dbresult; public bool Exists(object primarykey) return dbset.find(primarykey) == null? false : true; public virtual int Insert(T entity) dynamic obj= dbset.add(entity); this._unitofwork.db.savechanges(); return obj.id; public virtual void Update(T entity) dbset.attach(entity); _unitofwork.db.entry(entity).state = EntityState.Modified; this._unitofwork.db.savechanges(); public int Delete(T entity) if (_unitofwork.db.entry(entity).state == EntityState.Detached)

dbset.attach(entity); dynamic obj=dbset.remove(entity); this._unitofwork.db.savechanges(); return obj.id; public IUnitOfWork UnitOfWork get return _unitofwork; internal DbContext Database get return _unitofwork.db; public IEnumerable<T> GetAll() return dbset.asenumerable().tolist(); public class ContactRepository: BaseRepository<Contact> public ContactRepository(IUnitOfWork unit):base(unit) public class AddressRepository : BaseRepository<Address> public AddressRepository(IUnitOfWork unit) : base(unit)

Testing driver private IUnitOfWork uow = null; private ContactRepository repo = null; uow = new UnitOfWork(); repo = new ContactRepository(uow); var contacts = repo.getall(); return View(contacts.ToList()); Contact contact = repo.singleordefault(id); repo.insert(contact); repo.update(contact); Contact contact = repo.singleordefault(id); repo.delete(contact); protected override void Dispose(bool disposing) uow.dispose(); base.dispose(disposing); You have to build the UnitOfWork class by implementing IUnitOfWork and this class will be responsible for creating the EF. Then the repository class (ContactRepository) will be initialized with the uow object.