#UnitofWork
Explore tagged Tumblr posts
Text
Generic Repository Pattern in C#
I just implemented the Code First Generic Repository Pattern in C#! Say goodbye to repetitive repository code đ Check out my implementation and let me know your thoughts! #CSharp #RepositoryPattern #CodeFirst #UnitofWork
Have you ever dreaded writing the same boilerplate repository code repeatedly? Youâre not alone; I will share my implementation of the Code First Generic Repository Pattern in C#. I will only include some of the code because it will make the post incredibly long. At the end of the post, I will share a Goal donation to post a Git download link so you can take it for a spin. As a bonus, theâŠ
#CodeEfficiency#CodeFirst#CRUDOperations#CSharp#DatabaseManagement#DbContext#DependencyInjection#DesignPatterns#EntityFramework#GenericRepository#Migrations#RepositoryPattern#SoftwareDevelopment#UnitofWork
0 notes
Link
Enterprise Design Patterns have been around for a while to represent best practices for large scale development projects. First promoted by Martin Fowler in 2003 â âPatterns of Enterprise Application Architectureâ. First Adapted to Salesforce by Andy Fawcett in 2014 â now known as âSalesforce Lightning Platform Enterprise Architecture, 3rd editionâ Agenda Review basic Object-Oriented Analysis and Development themes Salesforce Lightning Enterprise Architecture patterns Selector Pattern Domain Pattern Service Pattern Unit of Work Pattern Application Factory Pattern Review of Apex Enterprise Patterns Open Source group and frameworks Apex Enterprise Design Patterns Open Source Frameworks originally created by FinancialForce FFLIB Apex Mocks An Apex mocking framework for true unit testing in Salesforce, with Stub API supportBased on the Java mocking framework Mockito FFLIB Apex Commons Framework which supports implementation of various Martin Fowler design patternsFFLIB frameworks are now maintained by the Apex Enterprise Patterns GitHub group https://github.com/apex-enterprise-patterns Basic OOAD Themes Various principles and themes used in enterprise application development: Separation of ConcernsDRY PrincipleSOLID PrincipleDependency Injection Separation of Concerns Enterprise software needs to change over time.  It evolves.Itâs one thing to write code to satisfy the immediate need.  Itâs another thing to write code that will be easy to maintain and be able to be changed over time.Complex code will become unmaintainable if proper boundaries are not established Typical layers include: Presentation Declarative: Lightning UI/LEX, Page layouts, Reports, Dashboards, Screen Flow Types Programmatic: Lightning Web Components, Aura, Single Page Apps, Visualforce Business Logic Layer Declarative: Certain elements of Flows and Process Builders, Approval Processes Programmatic: Apex Data Access Layer Declarative: Flow Data Elements â Create Records, Update Records, Get Records, etc Programmatic: SOQL, SOSL, Salesforce REST and SOAP APIs Database Layer Declarative: Custom Objects, Fields, Relationships, Autolaunched Flow Types Programmatic: Apex Triggers DRY Principle âDonât repeat yourselfâ âEvery piece of knowledge must have a single, unambiguous, authoritative representation within a systemâ SOLID Principle Single-responsibility principle A piece of logic should only have a single responsibilityâŠ.and that responsibility should be entirely encapsulated by the class, module or function. Open-closed principle âSoftware entities ⊠should be open for extension but closed for modification.â Liskov substitution principle âObjects in a program should be replaceable with instances of their subtypes without altering the correctness of that programâ âDesign by Contractâ Interface segregation principle âMany client-specific interfaces are better than one general-purpose interface.â  Donât force a class to depend on methods that it does not use. Dependency inversion principle âDepend on abstractions and not concretionsâ Dependency Injection Technique in which an object receives things that it depends on at runtime. Separates the creation of a dependency from the usage of a dependency Promotes the concept of âloosely coupledâ system Selector Pattern A class responsible for all aspects of queries for a single SObject. It manages the fields to query and manages the specific queries. All classes use this class to make queries against this SObject. The pattern encourages bulkification. All method parameters are usually Sets of IDs and return Lists of the SObject. Returns List of SObjects or Database.QueryLocator. Domain Pattern A class responsible for the business logic specific to a single SObject. Sometimes viewed as âfine grain servicesâ. It is a wrapper around the records you are working with. Initialize the domain class with all of the records of that type that you are working with in the current context.  This can be one to many records. It does not manage the persistence of records (see UnitOfWork). Handles defaulting and validations. Once you have the domain class, you work with a single object, executing logic on the records. Service Pattern A class responsible for aggregating the logic across multiple SObjects Sometimes viewed as a âcourse-grained serviceâ This is the traditional âService Tier Contractâ boundary All Presentation or âclient-tierâ logic calls the Service Tier logic Typically, the âclient-tierâ logic only calls a single Service method per transaction Becomes the DML Transaction boundary by utilizing a UnitOfWork (see UnitOfWork pattern) Unit Of Work Pattern A âutilityâ class focused on Optimizing DML interactions with the Database layer Providing transactional control for the Service Layer Simplifying the complex code usually constructed to manage bulkified DML operations Managing the âplumbingâ needed to save parent-child data relationships Used within a service method but passed to domain methods as needed. The UOW manages all DML transactions and rollbacks for all Service Layer logic Using an instance of UOW, you can register new records, modified/dirty records, and register records that need to be deleted. Once all records and changes are collected, the âcommitWork()â method is called to begin DML transactions. UOW manages relationships between parent and child records Since the UOW only holds records until the end of the Service method and the call to the âcommitWork()â method, it needs to maintain the âconnectionâ between parent and child records. The âregisterRelationshipâ series of methods accomplish this. Reference line 54 of the InvoicingServiceTest class. The parent Opportunity record is registered at line 39 âŠbut not saved to database yet Each of the child OpportunityLineItem records are Registered as new records to be saved at line 55 Related to the parent Opportunity record at line 54 using the âregisterRelationshipâ method During the âcommitWork()â method execution, the UOW saves the parent Opportunity records, maintains a link to the new opportunity record id, and then adds that parent record id to the child OpportunityLineItem records before saving those new records. Recording Date    : Sat, AUG 22, 2020 10:00 AM EST (7:30 PM IST) Where : Apex Hours Youtube Live Speaker :  John M. Daniel Further learning Apex Enterprise Patterns â Separation of Concerns https://andyinthecloud.com/2012/11/16/apex-enterprise-patterns-separation-of-concerns/ Apex Enterprise Patterns â Selector Layer https://andyinthecloud.com/2013/09/09/apex-enterprise-patterns-selector-layer/ Apex Enterprise Patterns â Domain Layer https://andyinthecloud.com/2013/04/24/apex-enterprise-patterns-domain-layer/ Apex Enterprise Patterns â Service Layer https://andyinthecloud.com/2013/02/11/apex-enterprise-patterns-service-layer/ Apex Enterprise Patterns â Unit Of Work http://andyinthecloud.com/2013/06/09/managing-your-dml-and-transactions-with-a-unit-of-work/ http://andyinthecloud.com/2014/07/17/doing-more-work-with-the-unit-of-work/ Apex Enterprise Patterns â FinancialForce Apex Common Updates https://andyinthecloud.com/2014/06/28/financialforce-apex-common-updates/ 123 total views, 123 views today The post Apex Enterprise Patterns appeared first on Apex Hours.
0 notes
Photo

Blazor WebAssembly, Integration of UnitOfWork â http://bit.ly/33qVOhp #Blazor #WebAssembly #dotnet
#WebAssembly#Web Development#Web Page#web development tutorial#Web Design#web design tutorial#web development tutorial for beginners#codequs#morioh
0 notes
Photo

Blazor WebAssembly, Integration of UnitOfWork â http://bit.ly/33qVOhp #Blazor #WebAssembly #dotnet
#WebAssembly#Web Development#Web Page#web development tutorial#Web Design#web design tutorial#web development tutorial for beginners#codequs#morioh
0 notes
Text
Láșp trĂŹnh viĂȘn (Junior Developer.Net)
https://ift.tt/3cjxanC - LĂ nhĂąn viĂȘn cá»§a VNIs: - PhĂĄt triá»n há» thá»ng hĂła ÄÆĄn Äiá»n tá» trĂȘn ná»n táșŁng .NET - XĂąy dá»±ng ASP.NET MVC, API, Windows Service, Single Page Application, Microservice ... - LĂ m Front-end vá»i HTML5, CSS3, JSON, XML, CSV, Bootstrap, AngularJS - LĂ m Back-end vá»i .Net Core, .Net Framework , Entity Framework, SQL Server, Redis cache, MessageQueue, Multiple thread - Thiáșżt káșż Database vá»i Indexes, Partition, Fragmentation, Job, Transaction, Store Procedure - LĂ m Dependency Injection, Design Pattern (Repository, UnitOfWork, Singleton, CQRS, Domain Driven Design, Module) ... - LĂ m vá» unit test, system test, load test, optimize souce code, security, performance, turning há» thá»ng - ÄÆ°á»Łc sá» dỄng SQL Server Profiler, Database Engine Turning Advisor ... - LĂ m viá»c theo phÆ°ÆĄng phĂĄp Agile Scrum #timviec #timvieconline #cv #cvxinviec #cvonlinetimviec #cv.timviec.com.vn #tuyendung
0 notes
Photo

Blazor WebAssembly, Integration of UnitOfWork â http://bit.ly/33qVOhp #Blazor #WebAssembly #dotnet
#WebAssembly#Web Development#Web Page#web development tutorial#Web Design#web design tutorial#web development tutorial for beginners#codequs#morioh
0 notes
Photo

Blazor WebAssembly, Integration of UnitOfWork â http://bit.ly/33qVOhp #Blazor #WebAssembly #dotnet
#WebAssembly#Web Development#Web Page#web development tutorial#Web Design#web design tutorial#web development tutorial for beginners#codequs#morioh
0 notes
Photo

Blazor WebAssembly, Integration of UnitOfWork â http://bit.ly/33qVOhp #Blazor #WebAssembly #dotnet
#WebAssembly#Web Development#Web Page#web development tutorial#Web Design#web design tutorial#web development tutorial for beginners#codequs#morioh
0 notes
Text
Multi-Tenant API Based on Swagger, Entity Framework Core With UnitOfWork, and Repository Patterns
There are a lot of options for building a scalable (multi-tenant) solution- for example, using Microsoft Elastic database (elastic tools). But these solutions are not suitable for some product requirements, or could contain some major disadvantages. This article will explain how to build multi-tenant applications/web APIs, step by step (based on the Horizontal Scaling type). https://goo.gl/aTXmzU #DataIntegration #ML
0 notes
Photo

Blazor WebAssembly, Integration of UnitOfWork â http://bit.ly/33qVOhp #Blazor #WebAssembly #dotnet
#WebAssembly#Web Development#Web Page#web development tutorial#Web Design#web design tutorial#web development tutorial for beginners#codequs#morioh
0 notes
Text
Implementing UnitOfWork And Repository Pattern
Repository pattern is extensively used in Web API projects. There is another concept called âUnitOfWorkâ which works with repository pattern. Today, I will show you a nice way to implement âUnitOfWorkâ with âRepository Patternâ. source https://www.c-sharpcorner.com/article/implementing-unitofwork-and-repository-pattern/ from C Sharp Corner https://ift.tt/2XopjPn
0 notes
Link
Evergreen: Serverless Functions & Compute for Customer 360 Platform  Delightful and cohesive digital experiences make for happy customers, partners and employees, and building those modern experiences requires direct and seamless access to Customer 360 data and business logic. Thatâs why weâre excited to announce Salesforce Evergreen â a new addition to the Customer 360 Platform that brings in serverless functions based on fully-managed Kubernetes, support for open programming languages and commonly used high-performance data stores. Evergreen is the best way to build the deep and engaging digital experiences that your customers have come to expect. Evergreen supports technologies and architectural patterns that make development teams productive and happy: Functions-as-a-Service for writing business logic and event processing in languages like Node.js, Java and Apex, using the full power of those languagesâ package ecosystems. Functions can be triggered directly from Apex or using Platform Events, with many more invocation types and event sources to come. Microservices for building serverless HTTP apps and APIs that can be quickly evolved by small agile teams and composed into complex, engaging digital experiences. Services and functions are serverless, consume no resources when idle and automatically and elastically scale with traffic. Managed data stores like Postgres, Apache Kafka and Redis that complement the Salesforce Data APIs for high-performance persistence and real-time eventing. As an industry first, these features come with built-in customer context, driven by the Salesforce data model and low-code components. Evergreen is a seamless part of the Salesforce platform and no extra authentication or networking setup is required. For example, developers can invoke functions directly from Apex, run logic with org-context and query and write-back updates. Evergreen is based on Kubernetes and balances control and access to scalable container technology by providing a fully managed serverless service operated by Salesforce. This service lets you focus more on innovation rather than infrastructure operations. Evergreen opens Salesforce development to any development team because apps, functions and services can be built using common open languages, tools and technologies. At the Dreamforce 2019 Developer Keynote, we showcased how Salesforce customers like Caesars Entertainment can build a modern guest check-in experience using Evergreen. In the keynote demo, the Lightning Platform is used to quickly create an employee-facing iOS app for managing housekeeping and room-readiness and that is seamlessly extended with event-driven functions running on Evergreen. When housekeeping marks a room as ready using the employee app, a platform event triggers a Node.js function that uses guest-context to send a tailored real-time notification letting the guest know that the room is ready for early check-in. At the end of the stay, the Salesforce Flow powering the guest checkout can call out to a different function with invoicing details. The Node.js function can use the invoice details and an npm PDF module to quickly generate a bill. Hereâs the sample function that receives the request as a CloudEvent fetches additional data, generates a PDF and adds a link to the PDF from the guest booking record: import { UnitOfWork, SObject } from '@salesforce/functions'; import { PDFDocument } from 'pdfkit'; import * as fs from 'fs'; module.exports = async function(event, context, logger) { const folioPayload = event.payload; // Creating a new Unit Of Work instance const uow = UnitOfWork; // Run SOQL query to fetch folio data const query = `SELECT Id, Description__c, Amount__c, Date__c FROM Booking_LineItems__c WHERE Reservation__c =:${folioPayload.recordId}`; const folioLineItems = await context.sfApi.query(query); // Call function to generate PDF and store in external data store // for Files Connect const pdfFilesConnect = await generatePdf( folioPayload.recordId, folioLineItems ); // Update the booking object const ReservationObject = new SObject('Reservation__c'); ReservationObject.Id = folioPayload.recordId; ReservationObject.Status__c = 'Paid and Folio created'; uow.registerModified(ReservationObject); // Update data uow.commit(); }; async function generatePdf(id, lineItems) { # generate and store folio PDF } Functions running on Evergreen idle when not in use and automatically scale to handle any invocation load or event throughput. Functions are easy to build from source with Cloud Native Buildpacks and developers are free to use any supported programming language and to pull in any package or library thatâs going to help them get their job done. Evergreen is the latest addition to the Salesforce Platform, combining Herokuâs decade-long experience building scalable container runtimes and high-performance data stores with Lightning tools and features. The unique combination of serverless, elastic container technology and seamless access to customer data and low-code business logic makes Salesforce the obvious place to build and run the differentiated digital experiences that impress your customers, partners and employees. A developer preview of Evergreen will be available with the Spring â20 release in February. Sign up to get Evergreen updates. You can also watch the Dreamforce Developer Keynote recording to see an Evergreen demo. If youâre joining us on-site at #DF19, drop by the Dreamforce Evergreen booth at Platform Park in the Trailhead area (At Moscone West) to learn more, or join us for these Evergreen-focused Dreamforce breakout sessions: Build More on the Salesforce Platform with Evergreen Functions: An Elastic Runtime for Node.js â Wed, Nov 20, (2:30-2:50pm), Moscone West (Surfside Theater) Salesforce Evergreen and Evergreen Functions: Build evented serverless consumer apps â Thurs, Nov 21 (3-3:40pm), Moscone West (Room 2007) Evented enterprise app architectures with Salesforce Evergreen and Evergreen Functions â Thurs, Nov 21 (5-5:40pm), Moscone West (Room 2024) Salesforce Evergreen and Evergreen Functions: Build evented serverless consumer apps â Fri, Nov 22, (12-12:40pm), Moscone West (Surfside Theater)
0 notes
Text
Implementing UnitOfWork And Repository Pattern
Repository pattern is extensively used in Web API projects. There is another concept called âUnitOfWorkâ which works with repository pattern. Today, I will show you a nice way to implement âUnitOfWorkâ with âRepository Patternâ. from C-Sharpcorner Latest Content https://ift.tt/2T4hVKb
from C Sharp Corner https://csharpcorner.tumblr.com/post/183094280781
0 notes
Text
Implementing UnitOfWork And Repository Pattern
Repository pattern is extensively used in Web API projects. There is another concept called âUnitOfWorkâ which works with repository pattern. Today, I will show you a nice way to implement âUnitOfWorkâ with âRepository Patternâ. from C-Sharpcorner Latest Content https://ift.tt/2T4hVKb
0 notes
Text
Using the Repository Pattern with the Entity Framework
Through this article, we are going to see how to use the Repository Pattern with the Entity Framework in an ASP.NET MVC application.
Introduction
The Repository Pattern, as well as the Unit of Work Pattern, allows to create an abstraction layer between the data access layer and the business logic layer of an application. The purpose of creating this layer is to isolate data access layer so that the changes we may operate cannot affect the business logic layer directly. Implementing these patterns is also helpful for automated unit testing or test-driven development.
The Repository Pattern
The Repository Pattern allows us to create an abstraction layer between the data access layer and the business logic layer of an application. So, this Data Access Pattern offers a more loosely coupled approach to data access. So, we are able to create the data access logic in a separate class, called a Repository, which has the responsibility of persisting the application's business model.
The Unit of Work Pattern
The Unit of Work Pattern is a pattern that handles the transactions during data manipulation using the Repository Pattern. Unit of Work is referred to as a single transaction that involves multiple operations.
Setting up our project
First, we have to set up our project. So, let's head to Visual Studio and choose "New Project > Visual C# > Web > ASP.NET We Application (.NET Framework)". Name our application "GameApplication".
Now, let's install the Entity Framework and enable Migrations:
PM> Install-Package EntityFramework -Version 6.2.0 PM> enable-migrations
Installing Entity Framework and enabling migrations
Enable Routes attributes:
routes.MapMvcAttributeRoutes();
Adding Attributes Routes in AppStart/RouteConfig.cs file_
We can now create our first Model, that we are going to name "Game", like so:
namespace GameApplication.Models { public class Game { public int Id { get; set; } public string Name { get; set; } } }
Models/Game.cs file
We now have to create a "DAL" folder at the root of our application where we are going to create a "GameContext" file.
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Web; using GameApplication.Models; namespace GameApplication.DAL { public class GameContext : DbContext { public GameContext() : base("GameContext") { } public DbSet<Game> Games { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } }
DAL/GameContext.cs file
Now, in the "Migrations/Configuration.cs" file, let's place the following code:
namespace GameApplication.Migrations { using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using GameApplication.Models; internal sealed class Configuration : DbMigrationsConfiguration<GameApplication.DAL.GameContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(GameApplication.DAL.GameContext context) { var games = new List<Game> { new Game{Name="Super Mario Bros"}, new Game{Name="Super Mario 64"}, new Game{Name="Super Mario Galaxy"} }; games.ForEach(e => context.Games.AddOrUpdate(p => p.Name, e)); context.SaveChanges(); } } }
Migrations/Configuration.cs file
We then have to make little changes in our "Web.config" file:
<connectionStrings> <add name="GameContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=GameApplication;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/> </connectionStrings>
Web.config file edited
Now, we are ready to create our first Controller. Let's choose the "MVC 5 Controller with views, using Entity Framework" option and name it "GameController". We can enter "Game" as the Model class and "GameContext" for the database Context. After a few seconds, we can see that a Controller with some code in it and a bunch of Views have been created for us.
Now, if we run our application and go to "localhost:RANDOMPORT/game_", we should see something interesting.
Generic Repository
There are many ways to implement the Repository Patterns. We could create a Repository Class for each entity type, but it results in a lot of redundant code or in partial updates. So, to avoid this, we are going to create a Generic Repository.
First, let's create a file named "GenericRepository.cs" in our "DAL" folder and fill it like so:
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using System.Web; using GameApplication.Models; namespace GameApplication.DAL { public class GenericRepository<TEntity> where TEntity : class { internal GameContext context; internal DbSet<TEntity> dbSet; public GenericRepository(GameContext context) { this.context = context; this.dbSet = context.Set<TEntity>(); } public virtual IEnumerable<TEntity> Get( Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "") { IQueryable<TEntity> query = dbSet; if (filter != null) { query = query.Where(filter); } foreach (var includeProperty in includeProperties.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } if (orderBy != null) { return orderBy(query).ToList(); } else { return query.ToList(); } } public virtual TEntity GetByID(object id) { return dbSet.Find(id); } public virtual void Insert(TEntity entity) { dbSet.Add(entity); } public virtual void Delete(object id) { TEntity entityToDelete = dbSet.Find(id); Delete(entityToDelete); } public virtual void Delete(TEntity entityToDelete) { if (context.Entry(entityToDelete).State == EntityState.Detached) { dbSet.Attach(entityToDelete); } dbSet.Remove(entityToDelete); } public virtual void Update(TEntity entityToUpdate) { dbSet.Attach(entityToUpdate); context.Entry(entityToUpdate).State = EntityState.Modified; } } }
DAL/GenericRepository.cs file
As we can see, first, we declare two class variables: one for the context and one for the entity set that the Repository is instantiated for. The constructor accepts a database context instance and initializes the entity set variable.
If we just overview the class, we can notice that the code declares a typical set of "CRUD" methods.
The signature of the "Get()" method can seem impressive. The first two arguments are lambda expressions. "Expression> filter" means that a lambda expression, based on "TEntity", will be provided and it will return a Boolean value. "Func, IOrderedQueryable> orderBy" also means that a lambda expression will be provided. The input of this expression is an "IQueryable" object and it will return an ordered version of that object. Finally, the third argument is a string that allows us to provide a comma-delimited list of navigation properties for eager loading. In the body of this method, we can see that, first, the filter expression is applied if there is one. Secondly, the eager-loading expression is performed. Finally, the order expression is applied if there is one.
Come next two methods, one to get an Entity by its ID, then a method that handles insertion. We then have two "Delete()" methods that manage the deletion. Finally, we find the "Update()" method.
Unit of Work
As we said, the role of the Unit of Work class is to make sure that, when we use multiple Repositories, they share a single database Context. So, when a Unit of Work is complete, the "SaveChanges()" method is called on the instance corresponding to the current Context. We are then assured that all related changes will be coordinated.
Let's create a file named "UnitOfWork.cs" in our "DAL" folder and fill it like so:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using GameApplication.Models; namespace GameApplication.DAL { public class UnitOfWork : IDisposable { private GameContext context = new GameContext(); private GenericRepository<Game> gameRepository; public GenericRepository<Game> GameRepository { get { return this.gameRepository ?? new GenericRepository<Game>(context); } } public void Save() { context.SaveChanges(); } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
DAL/UnitOfWork.cs file
If we look at the code, we can see that the class implements the "IDisposable" interface. The main purpose of this interface is to release unmanaged resources. A managed resource means "managed memory" that is managed by the garbage collector. When we no longer have any references to a managed object, which uses managed memory, the garbage collector will release that memory for us. So, unmanaged resources are everything that the garbage collector does not know about (open files, open network connections, etc.). So, using the "Dispose()" method of this interface allows us to release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.
We also have a class variable for the database Context and another for the Repository we are going to use. If there were more Repositories, we would have to add variables representing each of them. We then perform a check to see if our Repository already exists. If not, we instantiate it using the Context instance.
The "Save()" method calls the "SaveChanges()" on the Context.
Changing the Controller
Now, let's go back to our "GameController" and change it like so:
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using GameApplication.DAL; using GameApplication.Models; namespace GameApplication.Controllers { public class GameController : Controller { private UnitOfWork unitOfWork = new UnitOfWork(); // GET: Game public ActionResult Index() { var games = unitOfWork.GameRepository.Get(); return View(games.ToList()); } // GET: Game/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Game game = unitOfWork.GameRepository.GetByID(id); if (game == null) { return HttpNotFound(); } return View(game); } // GET: Game/Create public ActionResult Create() { return View(); } // POST: Game/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Id,Name")] Game game) { if (ModelState.IsValid) { unitOfWork.GameRepository.Insert(game); unitOfWork.Save(); return RedirectToAction("Index"); } return View(game); } // GET: Game/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Game game = unitOfWork.GameRepository.GetByID(id); if (game == null) { return HttpNotFound(); } return View(game); } // POST: Game/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Name")] Game game) { if (ModelState.IsValid) { unitOfWork.GameRepository.Update(game); unitOfWork.Save(); return RedirectToAction("Index"); } return View(game); } // GET: Game/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Game game = unitOfWork.GameRepository.GetByID(id); if (game == null) { return HttpNotFound(); } return View(game); } // POST: Game/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Game game = unitOfWork.GameRepository.GetByID(id); unitOfWork.GameRepository.Delete(id); unitOfWork.Save(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { unitOfWork.Dispose(); } base.Dispose(disposing); } } }
Controllers/GameController.cs file edited
Here, we add a class variable for the "UnitOfWork". One improvement we could do here is to use the constructor instead or to use Dependency Injection. The main change is that every reference to the database Context is replaced by a reference to the appropriate Repository, using "UnitOfWork" properties to access the Repository.
If we run our application again, we see that it looks and works the same as before.
Conclusion
Through this article, we defined the Repository and the Unit of Work patterns. We saw which concept they encapsulate and how we can use them in our application.
One last word
If you like this article, you can consider supporting and helping me on Patreon! It would be awesome! Otherwise, you can find my other posts on Medium and Tumblr. You will also know more about myself on my personal website. Until next time, happy headache!
0 notes
Text
Repository And UnitOfWork Pattern - Part One
Repository as it implies is a place where things are stored and can be found and retrieved whenever needed. Similarly, in computing terms, repository is a central location in which data for a specific type of entity or entities is stored and managed either in a form of collection or table. source https://www.c-sharpcorner.com/article/repository-and-unitofwork-pattern-part-1/ from C Sharp Corner https://ift.tt/2vYhBym
0 notes