repository pattern and unit of work with entity framework in asp.docx

Upload: zoranmatusko

Post on 27-Feb-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    1/19

    Repository Pattern and Unit of Work with Entity Framework in ASP.NETMVC

    In previous tutorial you used basic CRUD (Create, Read, Update and Delete)functionality with entity framework and by using !uery dialog(s) in asp"net

    mvc" In this you#ll see some ways to use the repository and unit of workpatterns for CRUD operations"$he repository and unit of work patterns are intended to create an abstractionlayer between the data access layer and the business logic layer of anapplication" Implementing these patterns can help insulate your applicationfrom changes in the data store and facilitate automated unit testing or test%driven development ($DD)"&et#s start with the implementation of Repository and Unit of 'ork patterns ina tutorial" If you have gone through my previous tutorial then start with whereit ends and if you do not have e perience about previous tutorial pleasedownload the sample of previous tutorial and start with that"

    ) In the current solution, add three new class library pro ect*a) +ample" odelb) +ample"Data"Contractsc) +ample"Data-ur solution e plorer will something look like this*

    anaging ulti .uery/orm +ample"Data +ample"Data"Contracts +ample" odel 0) Delete Category, +ubCategory and 1roduct class from the web pro ecti"e" anaging ulti .uery/orm and add these classes in Samp e.Mode pro ect" 2lso add reference of System.ComponentMode .!ataAnnotations in order to use the (Re!uired and Display) attribute" a) Cate"ory class (Category"cs)*

    public class Category 3 public int CategoryID 3 get 4set 4 5

    6Re!uired 7 public string 8ame 3 get 4set 4 5 5b) S#$Cate"ory class (+ubCategory"cs)* public class +ubCategory 3

    http://rohit-developer.blogspot.in/2014/08/crud-multiple-jquery-dialogs-in-aspnet.htmlhttp://rohit-developer.blogspot.in/2014/08/crud-multiple-jquery-dialogs-in-aspnet.htmlhttp://rohit-developer.blogspot.in/2014/08/crud-multiple-jquery-dialogs-in-aspnet.htmlhttp://rohit-developer.blogspot.in/2014/08/crud-multiple-jquery-dialogs-in-aspnet.htmlhttp://rohit-developer.blogspot.in/2014/08/crud-multiple-jquery-dialogs-in-aspnet.htmlhttp://rohit-developer.blogspot.in/2014/08/crud-multiple-jquery-dialogs-in-aspnet.html
  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    2/19

    public int +ubCategoryID 3 get 4set 4 5

    public virtual Category Category 3 get 4set 4 5

    6Display (8ame 9 :Category: )7

    public int CategoryID 3 get 4set 4 5

    6Re!uired 7 public string 8ame 3 get 4set 4 5 5c) Prod#%t class (1roduct"cs)* public class 1roduct 3 public int 1roductID 3 get 4set 4 5

    6Re!uired 7 public string 8ame 3 get 4set 4 5

    6Re!uired 7 public string Description 3 get 4set 4 5

    public virtual +ubCategory +ubCategory 3 get 4set 4 5

    6Display (8ame 9 :+ub Category: )7 public int +ubCategoryID 3 get 4set 4 5 5 ;) In +ample"Data"Contracts add two interface IRepository (forrepositories) and I1roductUow ( for unit of work)" where $* class 3 I.ueryable =$> ?et2ll()4 $ ?et

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    3/19

    IRepository =+ubCategory > +ubCategories 3 get 4 5 5A) In Samp e.!ata pro ect, add the reference of +ample" odel and+ample"Data"Contracts and install entity framework via package managerconsole ($ools B &ibrary 1ackage anager B 1ackage anager Console) by

    using following command*&nsta 'pa%ka"e entityframework

    ) Delete 1roductDbConte t, 1roductDbConte tInitiali er from the webpro ect and add these classes in Samp e.!ata pro ect* a) Prod#%t!$Conte(t class (1roductDbConte t"cs)* public class 1roductDbConte t * DbConte t 3 public 1roductDbConte t() * base (name-rConnection+tring* :Data +ource9+-8E%F2I-GG+.&H 1RH++4Initial Catalog91roductDbConte t4Integrated+ecurity9true4: ) 3 Database "+etInitiali er( new 1roductDbConte tInitiali er ())4 5

    protected override void -n odelCreating( Db odel 3

    protected override void +eed( 1roductDbConte t conte t) 3 &ist=Category > categories 9 new &ist=Category > 3 new Category 3 8ame 9 :/ood: 5, new Category 3 8ame 9 :Hlectronics: 5, new Category 3 8ame 9 : subcategories 9 new &ist=+ubCategory > 3

    new +ubCategory 3 8ame 9 :Fegetables: , Category 9categories"/ind(m 9> m"8ame"H!uals( :/ood: )) 5,

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    4/19

    new +ubCategory 3 8ame 9 :/ruits: , Category 9 categories"/ind(m9> m"8ame"H!uals( :/ood: )) 5, new +ubCategory 3 8ame 9 :Computer: , Category 9categories"/ind(m 9> m"8ame"H!uals( :Hlectronics: )) 5, new +ubCategory 3 8ame 9 :$elevision: , Category 9

    categories"/ind(m 9> m"8ame"H!uals( :Hlectronics: )) 5, new +ubCategory 3 8ame 9 :Cold Drinks: , Category 9categories"/ind(m 9> m"8ame"H!uals( : m"8ame"H!uals( :Fegetables: )) 5, new 1roduct 3 8ame 9 :2pple: , Description 9 :2pple: , +ubCategory9 subcategories"/ind(m 9> m"8ame"H!uals( :/ruits: )) 5, new 1roduct 3 8ame 9 :Desktop: , Description 9 :Desktop: ,+ubCategory 9 subcategories"/ind(m 9> m"8ame"H!uals( :Computer: )) 5, new 1roduct 3 8ame 9 :&?: , Description 9 :&?: , +ubCategory 9subcategories"/ind(m 9> m"8ame"H!uals( :$elevision: )) 5, new 1roduct 3 8ame 9 :+prite: , Description 9 :+prite: , +ubCategory9 subcategories"/ind(m 9> m"8ame"H!uals( :Cold Drinks: )) 5, new 1roduct 3 8ame 9 :Jingfisher: , Description 9 :Jingfisher: ,+ubCategory 9 subcategories"/ind(m 9> m"8ame"H!uals( : conte t"+ubCategory"2dd(m))4 products"/orHach(m 9> conte t"1roduct"2dd(m))4

    conte t"+aveChanges()4

    base "+eed(conte t)4 5 5

    c) Create new EFRepository class which implements &Repository interface for doing CRUD by using entity framework* @@@ =summary> @@@ $he H/%dependent, generic repository for data access @@@ =@summary> @@@ =typeparam name9:$:> $ype of entity for this Repository" =@typeparam> public class H/Repository =$> * IRepository =$> where $ * class 3 public H/Repository( DbConte t dbConte t) 3 if (dbConte t 99 null)

    throw new 2rgument8ullH ception (:dbConte t: )4 DbConte t 9 dbConte t4

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    5/19

    Db+et 9 DbConte t"+et=$>()4 5

    protected DbConte t DbConte t 3 get 4set 4 5

    protected Db+et =$> Db+et 3 get 4set 4 5

    public virtual I.ueryable =$> ?et2ll() 3 return Db+et4 5

    public virtual $ ?et

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    6/19

    Db+et"Remove(entity)4 5 5

    public virtual void Delete( int id)

    3 var entity 9 ?et public interface IRepository1rovider 3 @@@ =summary> @@@ ?et and set the =see cref9:DbConte t:@> with which to initiali e arepository @@@ if one must be created" @@@ =@summary> DbConte t DbConte t 3 get 4set 4 5

    @@@ =summary> @@@ ?et an =see cref9:IRepository3$5:@> for entity type, $" @@@ =@summary> @@@ =typeparam name9:$:> @@@ Root entity type of the =see cref9:IRepository3$5:@> " @@@ =@typeparam> IRepository =$> ?etRepository/orHntity$ype=$>() where $ * class 4

    @@@ =summary> @@@ ?et a repository of type $" @@@ =@summary>

    @@@ =typeparam name9:$:> @@@ $ype of the repository, typically a custom repository interface"

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    7/19

    @@@ =@typeparam> @@@ =param name9:factory:> @@@ 2n optional repository creation function that takes a =seecref9:DbConte t:@> @@@ and returns a repository of $" Used if the repository must be created"

    @@@ =@param> @@@ =remarks> @@@ &ooks for the re!uested repository in its cache, returning if found" @@@ If not found, tries to make one with the factory, fallingback to @@@ a default factory if the factory parameter is null" @@@ =@remarks> $ ?etRepository=$>( /unc =DbConte t , ob ect> factory 9 null) where $ *class 4

    @@@ =summary> @@@ +et the repository to return from this provider" @@@ =@summary> @@@ =remarks> @@@ +et a repository if you donMt want this provider to create one" @@@ Useful in testing and when developing without a backend @@@ implementation of the ob ect returned by a repository of type $" @@@ =@remarks> void +etRepository=$>($ repository)4 5 b) RepositoryPro,ider.%s

    @@@ =summary> @@@ 1rovides an =see cref9:IRepository3$5:@> for a client re!uest" @@@ =@summary> @@@ =remarks> @@@ Caches repositories of a given type so that repositories are only createdonce per provider" @@@ 1roduct application creates a new provider per client re!uest" @@@ =@remarks> public class Repository1rovider * IRepository1rovider

    3 public Repository1rovider( Repository/actories repository/actories) 3 Nrepository/actories 9 repository/actories4 Repositories 9 new Dictionary =$ype , ob ect>()4 5

    @@@ =summary> @@@ ?et and set the =see cref9:DbConte t:@> with which to initiali e arepository @@@ if one must be created"

    @@@ =@summary> public DbConte t DbConte t 3 get 4set 4 5

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    8/19

    @@@ =summary>

    @@@ ?et or create%and%cache the default =see cref9:IRepository3$5:@> foran entity of type $" @@@ =@summary>

    @@@ =typeparam name9:$:> @@@ Root entity type of the =see cref9:IRepository3$5:@> " @@@ =@typeparam> @@@ =remarks> @@@ If canMt find repository in cache, use a factory to create one" @@@ =@remarks> public IRepository =$> ?etRepository/orHntity$ype=$>() where $ * class 3 return ?etRepository= IRepository =$>>( Nrepository/actories"?etRepository/actory/orHntity$ype=$>())4 5

    @@@ =summary> @@@ ?et or create%and%cache a repository of type $" @@@ =@summary> @@@ =typeparam name9:$:> @@@ $ype of the repository, typically a custom repository interface" @@@ =@typeparam> @@@ =param name9:factory:> @@@ 2n optional repository creation function that takes a DbConte targument @@@ and returns a repository of $" Used if the repository must be createdand @@@ caller wants to specify the specific factory to use rather than one @@@ of the in ected =see cref9:Repository/actories:@> " @@@ =@param> @@@ =remarks> @@@ &ooks for the re!uested repository in its cache, returning if found" @@@ If not found, tries to make one using =see cref9: akeRepository3$5:@> " @@@ =@remarks> public virtual $ ?etRepository=$>( /unc =DbConte t , ob ect> factory 9null) where $ * class

    3 @@ &ook for $ dictionary cache under typeof($)" ob ect repo-b 4 Repositories"$ry?etFalue( typeof ($), out repo-b )4 if (repo-b K9 null) 3 return ($)repo-b 4 5

    @@ 8ot found or null4 make one, add to dictionary cache, and return it" return akeRepository=$>(factory, DbConte t)4

    5

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    9/19

    @@@ =summary> @@@ ?et the dictionary of repository ob ects, keyed by repository type" @@@ =@summary> @@@ =remarks> @@@ Caller must know how to cast the repository ob ect to a useful type"

    @@@ =p> $his is an e tension point" Eou can register fully made repositorieshere @@@ and they will be used instead of the ones this provider would otherwisecreate" =@p> @@@ =@remarks> protected Dictionary =$ype , ob ect> Repositories 3 get 4private set 4 5

    @@@ =summary> ake a repository of type $" =@summary> @@@ =typeparam name9:$:> $ype of repository to make" =@typeparam> @@@ =param name9:dbConte t:> @@@ $he =see cref9:DbConte t:@> with which to initiali e the repository" @@@ =@param>

    @@@ =param name9:factory:> @@@ /actory with =see cref9:DbConte t:@> argument" Used to make therepository" @@@ If null, gets factory from =see cref9:Nrepository/actories:@> " @@@ =@param> @@@ =returns>=@returns> protected virtual $ akeRepository=$>( /unc =DbConte t , ob ect>factory, DbConte t dbConte t) 3 var f 9 factory OO Nrepository/actories"?etRepository/actory=$>()4 if (f 99 null) 3 throw new 8otImplementedH ception (:8o factory for repositorytype, : P typeof ($)"/ull8ame)4 5 var repo 9 ($)f(dbConte t)4 Repositories6 typeof ($)7 9 repo4 return repo4 5

    @@@ =summary> @@@ +et the repository for type $ that this provider should return" @@@ =@summary> @@@ =remarks> @@@ 1lug in a custom repository if you donMt want this provider to createone" @@@ Useful in testing and when developing without a backend @@@ implementation of the ob ect returned by a repository of type $" @@@ =@remarks> public void +etRepository=$>($ repository) 3

    Repositories6 typeof ($)7 9 repository4 5

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    10/19

    @@@ =summary>

    @@@ $he =see cref9:Repository/actories:@> with which to create a newrepository" @@@ =@summary>

    @@@ =remarks> @@@ +hould be initiali ed by constructor in ection @@@ =@remarks> private Repository/actories Nrepository/actories4

    5 c) RepositoryFa%tories.%s @@@ =summary> @@@ 2 maker of 1roduct app Repositories" @@@ =@summary> @@@ =remarks> @@@ 2n instance of this class contains repository factory functions for differenttypes" @@@ Hach factory function takes an H/ =see cref9:DbConte t:@> and returns @@@ a repository bound to that DbConte t" @@@ =para> @@@ Designed to be a :+ingleton:, configured at web application start with @@@ all of the factory functions needed to create any type of repository" @@@ +hould be thread%safe to use because it is configured at app start, @@@ before any re!uest for a factory, and should be immutable thereafter" @@@ =@para> @@@ =@remarks> public class Repository/actories 3 @@@ =summary> @@@ Return the runtime 1roduct app repository factory functions, @@@ each one is a factory for a repository of a particular type" @@@ =@summary> @@@ =remarks> @@@ -DI/E $QI+ H$Q-D $- 2DD CU+$- /2C$-RE /U8C$I-8+ @@@ =@remarks>

    private IDictionary =$ype , /unc =DbConte t , ob ect>>?et1roduct/actories() 3 return new Dictionary =$ype , /unc =DbConte t , ob ect>> 3

    54 5

    @@@ =summary> @@@ Constructor that initiali es with runtime repository factories

    @@@ =@summary> public Repository/actories()

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    11/19

    3 Nrepository/actories 9 ?et1roduct/actories()4 5

    @@@ =summary>

    @@@ Constructor that initiali es with an arbitrary collection of factories @@@ =@summary> @@@ =param name9:factories:> @@@ $he repository factory functions for this instance" @@@ =@param> @@@ =remarks> @@@ $his ctor is primarily useful for testing this class @@@ =@remarks> public Repository/actories( IDictionary =$ype , /unc =DbConte t , ob ect>>factories) 3 Nrepository/actories 9 factories4 5

    @@@ =summary> @@@ ?et the repository factory function for the type" @@@ =@summary> @@@ =typeparam name9:$:> $ype serving as the repository factory lookupkey"=@typeparam> @@@ =returns> $he repository function if found, else null" =@returns> @@@ =remarks> @@@ $he type parameter, $, is typically the repository type @@@ but could be any type (e"g", an entity type) @@@ =@remarks> public /unc =DbConte t , ob ect> ?etRepository/actory=$>() 3

    /unc =DbConte t , ob ect> factory4 Nrepository/actories"$ry?etFalue( typeof ($), out factory)4 return factory4 5

    @@@ =summary> @@@ ?et the factory for =see cref9:IRepository3$5:@> where $ is an entitytype" @@@ =@summary> @@@ =typeparam name9:$:> $he root type of the repository, typically anentity type" =@typeparam> @@@ =returns> @@@ 2 factory that creates the =see cref9:IRepository3$5:@> , given an H/=see cref9:DbConte t:@> " @@@ =@returns> @@@ =remarks>

    @@@ &ooks first for a custom factory in =see cref9:Nrepository/actories:@> " @@@ If not, falls back to the =see

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    12/19

    cref9:DefaultHntityRepository/actory3$5:@> " @@@ Eou can substitute an alternative factory for the default one by adding @@@ a repository factory for type :$: to =see cref9:Nrepository/actories:@> " @@@ =@remarks> public /unc =DbConte t , ob ect>

    ?etRepository/actory/orHntity$ype=$>() where $ * class 3 return ?etRepository/actory=$>() OODefaultHntityRepository/actory=$>()4 5

    @@@ =summary> @@@ Default factory for a =see cref9:IRepository3$5:@> where $ is an entity" @@@ =@summary> @@@ =typeparam name9:$:> $ype of the repositoryMs rootentity =@typeparam> protected virtual /unc =DbConte t , ob ect>DefaultHntityRepository/actory=$>() where $ * class 3 return dbConte t 9> new H/Repository =$>(dbConte t)4 5

    @@@ =summary> @@@ ?et the dictionary of repository factory functions" @@@ =@summary> @@@ =remarks> @@@ 2 dictionary key is a +ystem"$ype, typically a repository type" @@@ 2 value is a repository factory function @@@ that takes a =see cref9:DbConte t:@> argument and returns @@@ a repository ob ect" Caller must know how to cast it" @@@ =@remarks> private readonly IDictionary =$ype , /unc =DbConte t , ob ect>>

    Nrepository/actories4

    5) Create Prod#%tUow class that implements I1roductUow in

    +ample"Data pro ect*

    @@@ =summary> @@@ $he 1roduct :Unit of 'ork: @@@ ) decouples the repos from the controllers @@@ 0) decouples the DbConte t and H/ from the controllers @@@ ;) manages the Uo' @@@ =@summary> @@@ =remarks> @@@ $his class implements the :Unit of 'ork: pattern in which @@@ the :Uo': serves as a facade for !uerying and saving to the database" @@@ .uerying is delegated to :repositories:" @@@ Hach repository serves as a container dedicated to a particular

    @@@ root entity type such as a =see cref9:1erson:@> " @@@ 2 repository typically e poses :?et: methods for !uerying and

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    13/19

    @@@ will offer add, update, and delete methods if those features aresupported" @@@ $he repositories rely on their parent Uo' to provide the interface to the @@@ data layer (which is the H/ DbConte t)" @@@ =@remarks>

    public class 1roductUow * I1roductUow , IDisposable 3 public 1roductUow( IRepository1rovider repository1rovider) 3 CreateDbConte t()4

    repository1rovider"DbConte t 9 DbConte t4 Repository1rovider 9 repository1rovider4 5

    @@ repositories

    public IRepository =1roduct > 1roducts 3 get 3 return ?et+tandardRepo= 1roduct >()4 5 5 public IRepository =Category > Categories 3 get 3 return ?et+tandardRepo= Category >()4 5 5 public IRepository =+ubCategory > +ubCategories 3 get 3 return ?et+tandardRepo= +ubCategory >()4 5 5

    @@@ =summary> @@@ +ave pending changes to the database @@@ =@summary> public void Commit() 3 DbConte t"+aveChanges()4 5

    protected void CreateDbConte t() 3 DbConte t 9 new 1roductDbConte t ()4 5

    protected IRepository1rovider Repository1rovider 3 get 4set 4 5 private IRepository =$> ?et+tandardRepo=$>() where $ * class

    3 return Repository1rovider"?etRepository/orHntity$ype=$>()4 5 private $ ?etRepo=$>() where $ * class 3 return Repository1rovider"?etRepository=$>()4 5

    private 1roductDbConte t DbConte t 3 get 4set 4 5

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    14/19

    Sregion IDisposable

    public void Dispose() 3 Dispose( true )4

    ?C "+uppress/inali e( this )4 5

    protected virtual void Dispose( bool disposing) 3 if (disposing) 3 if (DbConte t K9 null) 3 DbConte t"Dispose()4 5 5 5

    Sendregion 5T) 8ow in order to use repository and unit of work in web applicationpro ect ( anaging ulti .uery/orm), configure 8in ect via package managerconsole, use of following command in order to configure 8in ect in anapplication*a" Install%package Nin e%tb" Install%package Nin e%t.MVC/

    ) Replace the ?lobal"asa "cs M,%App i%ation class with the following* public class vc2pplication * 8in ectQttp2pplication 3 protected override IJernel CreateJernel() 3 var kernel 9 new +tandardJernel ()4

    kernel"()"$o= Repository/actories >() "In+ingleton+cope()4

    kernel"()"$o= Repository1rovider >()4 kernel"()"$o= 1roductUow >()4

    return kernel4 5

    protected override void -n2pplication+tarted() 3 2reaRegistration "Register2ll2reas()4

    /ilterConfig "Register?lobal/ilters( ?lobal/ilters "/ilters)4 RouteConfig "RegisterRoutes( Route$able "Routes)4

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    15/19

    5 5

    V) &ast and final step, create a 0aseContro er and inherit it in all(1roductController, CategoryController and +ubCategoryController)controllers in order to use I1roductUow*

    a)

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    16/19

    6Qttp1ost , Falidation2ction/ilter 7 public 1artialFiewResult Hdit(1roduct model) 3 Uow"1roducts"Update(model)4 Uow"Commit()4

    return 2dd()4

    5

    6Qttp1ost 7 public WsonResult Delete( int id) 3 var product 9 Uow"1roducts"?et

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    17/19

    3 return 1artialFiew( :NCategory&ist: , Uow"Categories"?et2ll()"'here(m9> m"8ame"Contains(s))"$o&ist())4 5

    public 1artialFiewResult 2dd() 3 return 1artialFiew( :NCategory: )4 5

    6Qttp1ost , Falidation2ction/ilter 7 public 1artialFiewResult 2dd( Category model) 3 Uow"Categories"2dd(model)4 Uow"Commit()4

    return 2dd()4 5

    6Qttp1ost 7 public WsonResult Delete( int id) 3 var category 9 Uow"Categories"?et

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    18/19

    subcategory"8ame 5, :application@ son: , WsonRe!uest

  • 7/25/2019 Repository Pattern and Unit of Work with Entity Framework in ASP.docx

    19/19

    I had taken a reference of Code Camper +pa application which is developedand thought by great Wohn 1apa "

    http://www.johnpapa.net/spa/http://www.johnpapa.net/spa/