using ado.net entity framework in domain driven design: a pattern approach

of 39 /39
Master thesis in Software Engineering and Management REPORT NO. 2008:016 ISSN: 1651-4769 Department of Applied Information Technology Using ADO.NET Entity Framework in Domain-Driven Design: A Pattern Approach ANDREY YEMELYANOV IT University of Göteborg Chalmers University of Technology and University of Gothenburg Göteborg, Sweden 2008

Author: hoan-phuc

Post on 10-May-2015

6.056 views

Category:

Technology


2 download

Embed Size (px)

DESCRIPTION

Tài liệu hướng dẫn ứng dụng ADO.NET Entity Framework vào thiết kế phần mềm theo DDD (Domain Driven Design)

TRANSCRIPT

  • 1.Master thesis in Software Engineering and ManagementREPORT NO. 2008:016ISSN: 1651-4769 Department of Applied Information TechnologyUsing ADO.NET Entity Framework in Domain-DrivenDesign: A Pattern Approach ANDREY YEMELYANOVIT University of Gteborg Chalmers University of Technology and University of GothenburgGteborg, Sweden 2008

2. Using ADO.NET Entity Framework in Domain-Driven Design: A Pattern ApproachANDREY YEMELYANOV ANDREY YEMELYANOV, 2008Report no. 2008:016ISSN: 1651-4769Department of Applied Information TechnologyIT University of GteborgChalmers University of Technology and University of GothenburgP O Box 8718SE 402 75 GteborgSwedenTelephone +46 (0) 31-772 4895I 3. Using ADO.NET Entity Framework in Domain-Driven Design: A Pattern ApproachANDREY YEMELYANOVDepartment of Applied Information TechnologyIT University of GteborgChalmers University of Technology and University of GothenburgSupervisor: Miroslaw StaronABSTRACTIn the object community domain-driven design philosophy has recently gained prominence. Theapplication of domain-driven design practices in iterative software development projects promises toconquer complexity inherent in building software. And with the reduced complexity comes moreintimate understanding of a problem domain, which results in better software, capable of effectivelyaddressing user needs and concerns. The ADO.NET Entity Framework with its emphasis on modelingconceptual business entities and handling persistence can potentially facilitate domain-driven design.However, it is not clear exactly how the framework should be used in the context of domain-drivendevelopment. This exploratory case study was commissioned by Volvo Information Technology (VolvoIT) and it sought to provide guidance on using the Entity Framework in domain-driven design at thecompany. The study produced a number of important results. Firstly, a total of 15 guidelines wereproposed for adopting the framework at Volvo IT. These guidelines address such issues as domainmodeling during requirements engineering, efficient mapping among various models, reverse-engineering of legacy databases, and a number of others. Secondly, six critical factors (performance,abstraction, competence, features, simplicity and support for multiple data sources) were identified thatmust be considered in adopting the Entity Framework in domain-driven design at the company. Finally,based on one of these factors, performance evaluation of the frameworks querying mechanisms wasperformed, which further strengthened the guidelines.KeywordsDomain-driven design, ADO.NET Entity Framework, persistence, domain model, patterns, object-relational impedance mismatch. II 4. ACKNOWLEDGEMENTSThis Master thesis has been a great exercise in knowledge discovery which would have been impossiblewithout:The Swedish Institute, whose kind support in cultural and monetary aspects has kept me goingthroughout my whole stay in Sweden. I would like to thank the Swedish Institute for granting me ascholarship to pursue my studies at the IT University.Miroslaw Staron Software Engineering and Management program manager at the IT University, whowas an academic supervisor of mine. Miroslaw provided valuable guidance on tackling the study mosteffectively. I would like to thank him for his patience, understanding and, most importantly, objectivecriticism of my work.Ludwik Wallin an architect at Volvo Information Technology, who was an industrial supervisor ofmine. Ludwik provided a valuable insight into the issues concerning building enterprise software andalso guided me towards relevant aspects of the Entity Framework and domain-driven design that need becarefully studied. I would also like to thank all the employees from the Software Process Improvementgroup and other departments at Volvo IT who contributed to this study with important interviews andinformal discussions.Thanks again to all of you for your help, time and willingness to share experience and insightfulcomments!Andrey YemelyanovMay 17, 2008Gothenburg, Sweden.III 5. TABLE OF CONTENTS1. INTRODUCTION................................................................................................................. 12. CASE STUDY DESIGN ....................................................................................................... 3 2.1 Context and Subjects ...................................................................................................... 3 2.2 Study Subjects................................................................................................................. 3 2.3 Data Collection and Analysis.......................................................................................... 3 2.4 Study Execution .............................................................................................................. 3 2.5 Threats to Validity .......................................................................................................... 43. RELATED WORK ............................................................................................................... 44. THEORETICAL FRAMEWORK ...................................................................................... 5 4.1 Structuring domain logic................................................................................................. 5 4.1.1Procedural style (Transaction Script)..................................................................... 6 4.1.2Domain Model style ................................................................................................ 7 4.2 Domain-driven design..................................................................................................... 7 4.2.1The building blocks of domain-driven design......................................................... 8 4.2.1.1Layered architecture............................................................................................ 8 4.2.1.2Entities ................................................................................................................ 8 4.2.1.3Services ............................................................................................................... 8 4.2.1.4Aggregates .......................................................................................................... 9 4.2.1.5Factories.............................................................................................................. 9 4.2.1.6Repository ........................................................................................................... 9 4.3 The ADO.NET Entity Framework.................................................................................. 9 4.3.1The building blocks of the Entity Framework......................................................... 9 4.3.1.1The Entity Data Model...................................................................................... 10 4.3.1.2Entity client ....................................................................................................... 10 4.3.1.3Entity SQL ........................................................................................................ 10 4.3.1.4Object Services ................................................................................................. 10 4.3.1.5LINQ to Entities................................................................................................ 10 4.3.2Accessing data via the Entity Framework and SQL Client................................... 11 4.3.3Concluding remarks.............................................................................................. 125. ADOPTING THE ENTITY FRAMEWORKIN DOMAIN-DRIVEN DESIGN: MAIN REQUIREMENTS .............................................. 12 5.1 Main goals..................................................................................................................... 12 5.2 Main requirements ........................................................................................................ 13IV 6. 5.3The role of the guidelines requirements........................................................................ 136.ENTITY FRAMEWORK IN DOMAIN-DRIVENDESIGN: CRUCIAL FACTORS .............................................................................................. 136.1Interviews...................................................................................................................... 136.2Factors........................................................................................................................... 136.3Data retrieval performance............................................................................................ 146.4Support for higher-level abstractions............................................................................ 146.5In-house competence level in objects, databases and object-relational mismatch........ 156.6Rich feature set ............................................................................................................. 156.7Simplicity...................................................................................................................... 156.8Support for heterogeneous data sources for the domain model .................................... 156.9Concluding remarks ...................................................................................................... 157.QUERY PERFORMANCE EVALUATION.................................................................... 167.1SqlDataReader .............................................................................................................. 177.2NHibernate .................................................................................................................... 177.3Entity Framework ......................................................................................................... 17 7.3.1Entity SQL............................................................................................................. 18 7.3.2LINQ to Entities .................................................................................................... 18 7.3.3Compiled LINQ to Entities ................................................................................... 187.4Analysis......................................................................................................................... 188.ENTITY FRAMEWORK GUIDELINES..198.1Pattern discovery process.............................................................................................. 208.2Core guidelines ............................................................................................................. 20 8.2.1Guideline 1: Business domain modeling............................................................... 20 8.2.2Guideline 2: Capturing domain logic ................................................................... 20 8.2.3Guideline 3: Expressing domain model in software ............................................. 20 8.2.4Guideline 4: Validating the domain model........................................................... 21 8.2.5Guideline 5: Applying the Aggregate pattern....................................................... 21 8.2.6Guideline 6: Applying the Repository pattern ...................................................... 21 8.2.7Guideline 7: Reverse engineering......................................................................... 21 8.2.8Guideline 8: Implementing business rules in the Entity Framework.................... 218.3Mapping patterns21 8.3.1Pattern: Object Association.................................................................................. 21 8.3.2Pattern: Object Aggregation................................................................................. 21 8.3.3Pattern: Object Composition ................................................................................ 21V 7. 8.3.4Pattern: Object Self-Association........................................................................... 21 8.3.5Pattern: Object Inheritance .................................................................................. 22 8.3.6Pattern: Domain Object........................................................................................ 22 8.3.7Pattern: Advanced Mapper................................................................................... 22 8.3.8Mapping pattern example ..................................................................................... 239.DISCUSSION ...................................................................................................................... 239.1Why patterns? ............................................................................................................... 239.2Initial evaluation ........................................................................................................... 2310. CONCLUSION ................................................................................................................... 2410.1 Key findings.................................................................................................................. 2410.2 Future research.............................................................................................................. 2411. ACKNOWLEDGMENTS .................................................................................................. 2512. REFERENCES.................................................................................................................... 25LIST OF FIGURESFigure 1: Part of a banking application built in a procedural style...6Figure 2: Transitioning from procedural database-drivendesign to domain-driven design7Figure 3: A navigation map of the language of domain-driven design.............................................8Figure 4: Layered architecture according to DDD8Figure 5: Aggregate...........................................................9Figure 6: Entity Framework architecture.10Figure 7: Order application relational schema.11Figure 8: Data access with the SQL Client..11Figure 9: Conceptual Entity Data Model builton top of the relational database schema in the order application...12Figure 10: Data access with LINQ in the Entity Framework...12Figure 11: Domain aggregate retrieved from the relational database..16Figure 12: Relational model underlying the Blog Aggregate..16Figure 13: SQL query to retrieve the Blog aggregate ..16Figure 14: SQL Client............................................................... .....................................................17Figure 15: hSQL in NHibernate ..17Figure 16: The Entity Data Model generated from the Blog relational model18Figure 17: Compiled LINQ to Entities query......18VI 8. Figure 18: A comparative evaluation of query performancewith DataReader, NHibernate and the Entity Framework....19Figure 19: Taxonomy of the Entity Framework Guidelines.....20Figure 20: Object association21Figure 21: Object aggregation...21Figure 22: Object composition..21Figure 23: Object self-association.22Figure 24: Table-Per-Hierarchy inheritance mapping...22Figure 25: Table-Per-Concrete-Class inheritance mapping......22Figure 26: Table-Per-Class inheritance mapping..22Figure 27: Multiple association.22Figure 28: Mapping to relational model22LIST OF APPENDICESAppendix A: Interview questions..................................................................................................27Appendix B: C# code to retrieve the Blog aggregate with the SQL client....29Appendix C: Example domain model based on domain-driven design principles.......................31 VII 9. Using ADO.NET Entity Framework in Domain-DrivenDesign: A Pattern Approach Andrey Yemelyanov IT University of Gteborg [email protected] the object community domain-driven design philosophy has hand, specifies how the given problem is to be solved. Crain [19]recently gained prominence. The application of domain-drivenrefers to this model as a platform-specific model because itdesign practices in iterative software development projects captures a mixture of behavior and technology. For example,promises to conquer complexity inherent in building software. the design model may include a JDBC 1class to specify how theAnd with the reduced complexity comes more intimate lifecycle of persistent business objects is handled.understanding of a problem domain, which results in betterSuch a seeming redundancy in models is necessary in order tosoftware, capable of effectively addressing user needs andensure a smooth transition from a problem space (use caseconcerns. The ADO.NET Entity Framework with its emphasis on specifications and analysis model) to a solution space (design andmodeling conceptual business entities and handling persistenceimplementation models), which is not trivial. Evans [22] arguescan potentially facilitate domain-driven design. However, it is not that once the implementation begins, analysis and design modelsclear exactly how the framework should be used in the context ofgrow increasingly disjoint. This happens because the analysisdomain-driven development. This exploratory case study wasmodel is created with no design issues in mind. Mixingcommissioned by Volvo Information Technology (Volvo IT) and implementation concerns into analysis models is considered badit sought to provide guidance on using the Entity Framework inpractice and is, therefore, highly discouraged. As a result, the puredomain-driven design at the company. The study produced a analysis model proves impractical for design purposes and isnumber of important results. Firstly, a total of 15 guidelines were abandoned as soon as programming begins [22]. There is a dangerproposed for adopting the framework at Volvo IT. Theseto such practice, Evans [22] continues. While analysis modelsguidelines address such issues as domain modeling duringmay accurately capture business needs and incorporate valuablerequirements engineering, efficient mapping among various knowledge about the problem domain, there is no guarantee thatmodels, reverse-engineering of legacy databases, and a number ofthe design model will successfully rediscover the insights gainedothers. Secondly, six critical factors (performance, abstraction, during analysis. Eventually, as the gap between the modelscompetence, features, simplicity and support for multiple datawidens, it becomes progressively difficult to feed insights fromsources) were identified that must be considered in adopting theanalysis into design.Entity Framework in domain-driven design at the company.Finally, based on one of these factors, performance evaluation of Domain-driven design (DDD) [22] vision seeks to bridge thethe frameworks querying mechanisms was performed, whichchasm between analysis and design by introducing a single modelfurther strengthened the guidelines.(domain model) that addresses both concerns. A domain modelnot only represents an important analysis artifact that capturesessential business concepts and constraints but also offers aKeywordsconcrete design in the form of object-oriented design classes.Domain-driven design, ADO.NET Entity Framework, persistence,Constituting an essential part of application design anddomain model, patterns, object-relational impedance mismatch. architecture, domain models in DDD are expressed in terms ofobject-oriented constructs such as classes, attributes, operations1. INTRODUCTION and relationships and are drawn with the UML class diagramIn a use-case driven software development process [3, 8, 14, 39]notation (see for example [22, 31] and Appendix C). Theseuse cases serve as a primary artifact for establishing system models may be referred to as domain object models or conceptualrequirements, validating system architecture, testing and models [25, 31]. We will henceforth refer to such models as justcommunicating with domain experts and other project domain models2. The basic premise behind DDD is thestakeholders [13]. Such a process is often used alongside with themaximization of knowledge about the domain. This is achieved byUnified Modeling Language (UML) [8]. After the use case a close cooperation between a project team and domain expertsspecification is fed into further development stages, two major with the goal of creating an explicit model of the problem domain.artifacts are conceived: analysis model and design model. There isAs a result, it is possible to reduce complexity inherent in mostan interesting dichotomy between the two models in that theyaddress two distinct dimensions (problem and solution) of thesame given domain. The analysis model represents the product of1analyzing a problem domain to organize its concepts. What roleJava Database Connectivity (JDBC) is a technology for connecting tothese concepts will play in software is not important in that relational databases from Java applications.2context [22]. It specifies what problem needs to be solved. The Note that in this thesis we address domain-driven design in the contextmajor content of the analysis model includes collaborations in theof business information systems. We do not consider DDD as applied inUML and analysis classes [19]. The design model, on the other embedded systems design or any other domain.1 10. businesses. This, in turn, should lead to better software thatshould occur, how models can be validated with the EF, or howeffectively supports business operations. DDD with the EF will affect requirements engineering stage.These, we believe, are important issues that must be considered.There is a challenge in using domain models in applications. Onthe one hand, to effectively model a complex business domain1.2 Thesis objectivewith all its valuable operation logic, domain models wouldThis exploratory study was commissioned by Volvo Informationnecessarily have to use a number of object-oriented constructs, Technology (Volvo IT) a subsidiary of the Volvo Corporationsuch as inheritance, aggregation/composition and design patterns. based in Gothenburg, Sweden. The impetus for Volvo IT to moveThese are so-called rich or deep domain models [22, 25]. On toward DDD practices with the EF is the potential reduction inthe other hand, to provide persistent storage of the domain model code complexity and further improvement of maintainability of itsstate, relational databases are widely used. The fact that theseenterprise applications. Accordingly, the objective of this study isdatabases use a relational data model to organize data places a to formulate guidance on applying the Entity Framework in DDDpractical limit on the richness of domain models [25]. This isin the context of an iterative software development process atcaused by a paradigm difference between object-oriented and Volvo IT. It addresses the following main research question:relational models, which in literature is referred to as object-relational impedance mismatch [7, 16, 18, 33, 38]. The basicHow should software development projects that emphasizepremise behind it is that objects and relations are fundamentally domain-driven design incorporate the Entity Framework fordifferent and their interplay is not trivial [38]. Fowler [25]domain modeling and domain object persistence?discusses structural and behavioral aspects of the impedanceThe main research question can be broken down into themismatch. In a structural sense, the author identifies two majorfollowing sub-questions:distinctions between objects and relations: identity andrelationships handling. From the behavioral perspective, aRQ1: What are the main goals behind the companys move toproblem arises when it comes to maintaining data in objects and further develop domain-driven design practices with the Entitytheir corresponding database tables in a consistent state. Issues Framework?that need to be considered, for example, are loading objects,ensuring no object for the same row is read more than once andRQ2: What are the most important factors that must be taken intohandling database updates. Due to impedance mismatch efficientaccount when adopting the Entity Framework in domain-drivenmapping of rich domain models to relational models presents a design in the company?problem.RQ3: What are the most important guidelines for adopting theEntity Framework in domain-driven software development in the1.1 Problem definitioncompany?While Evans [22] stresses that DDD is a set of principles focusingon modeling a business domain and needs no technological andThe thesis achieved a number of important results. Firstly, a set ofmethodological support other than object orientation, we believe15 guidelines were proposed for adopting the EF at Volvo IT.that effective adoption of DDD practices is contingent on the These guidelines address such issues as domain modeling duringavailability of tools. Essentially, such a tool would need to requirements engineering, efficient mapping between domaindirectly support domain modeling activity and offer concretemodels and the EDM, reverse-engineering of legacy databases,solutions to overcoming object-relational mismatch. In the late and a number of others. Secondly, a number of critical factors2007, Microsoft Corporation announced the Beta 3 release of the were identified that must be considered in using the EF withADO.NET Entity Framework (further abbreviated to EF or just DDD. Based on one of these factors, performance evaluation ofreferred to as Entity Framework) [34]. The EF is .NET-based EF querying mechanisms was performed, which furthermiddleware that represents an abstraction layer that promises tostrengthened the guidelines.alleviate impedance mismatch by decoupling application domainmodels from underlying relational storage models. A 1.3 Dispositiondistinguishing characteristic of the EF is the built-in support for The remainder of the report is structured as follows. Section 2development based on an explicit model. It introduces the Entitydiscusses the research methodology used in the study. Section 3Data Model (EDM), which captures essential business (domain)presents a brief overview of the related work. Section 4 delvesentities and their relationships in an explicit conceptual model. into the theoretical framework which served as the knowledgefoundation for the study. Section 5 addresses RQ1 by presentingThe EF can potentially facilitate DDD as it not only largelymain goals of moving to DDD practices with the Entityovercomes object-relational mismatch but also promotes model- Framework at Volvo IT. This section also discusses importantbased development of business applications. The resulting requirements that the guidelines have to fulfill. Section 6adoption of DDD in software development promises to raise the addresses RQ2 and presents critical factors that must be taken intoquality of delivered software. However, it is not clear how the consideration when adopting the Entity Framework for DDD atfeature set offered by the EF can support the DDD practices. To Volvo IT. Section 7 builds upon the preceding section andour best knowledge, no guidance has been published on how the presents the evaluation of the most important factor queryEF should be effectively integrated into a software development performance. Section 8 presents the overview of the Entityprocess with a particular emphasis on DDD. To date, one credibleFramework Guidelines (RQ3). Section 9 offers some furthersource on the EF is the documentation released by Microsoft [35]. reflections on the guidelines. Finally, Section 10 ends the reportHowever, it is limited to programming scenarios and by presenting important conclusions and outlining recommendedwalkthroughs. There exists no formal advice on mapping betweenfuture research.models should be performed, how and when domain modeling2 11. 2. CASE STUDY DESIGNconfidentiality agreement with Volvo IT, the guidelines developedThe main purpose of this study was to design a set of guidelinesin the thesis are a proprietary asset of the company and, therefore,for incorporating the EF into a domain-driven softwareonly their outline will be presented in this report.development process at Volvo IT. We used a qualitative2.2 Study Subjectsexploratory case study as the methodology behind the studyThe subjects in the case study were 1 senior .NET architect, 3design [48]. Exploratory case studies are suitable for performing software architects and 2 system analysts. The senior .NETpreliminary studies where it is not clear which phenomena are architect provided much-needed guidance on identifying realsignificant to look into, or how to quantitatively assess these industrial problems with regards to domain-driven developmentphenomena [21]. Moreover, to our best knowledge, research and object-relational mismatch. He outlined importantconcerning the adoption of Entity Framework in domain-drivenbenchmarks and requirements that the guidelines had to satisfy.development is non-existent and current literature provides noThe rationale for selecting other software architects as primaryconceptual framework for theorizing. This circumstance makessubjects was their first-hand exposure to object modeling andthe formulation of a proper hypothesis or theory prior to persistence. These architects provided critical data that allowed uscommencing the study difficult. Another justifiable rationale for to identify common object modeling and persistence mechanisms,choosing an exploratory case study is the descriptive nature of their characteristics, and also factors affecting the adoption ofresearch questions. Rather than asking to provide causative links Entity Framework at Volvo IT. In involving system analysts in the(why?), research objectives in this study mainly focus on so-called study we sought to identify common methods and techniques usedwhat?-questions where the major goal is to develop hypotheses for requirements modeling in the company. In this way, we couldfor further scientific inquiry. see whether system analysis (in which domain modeling shouldThe research paradigm of this case study can be characterized asplay an important part) placed any limitations on using pureinterpretive. Unlike positivist approach where reality can be domain-driven design approaches in building businessobjectively described with measurable properties, interpretiveapplications.paradigm seeks to gain knowledge through less preciseconstructions such as language and shared meanings [9, 41]. It is2.3 Data Collection and AnalysisTo increase overall reliability of the study a method of dataparticularly applicable in cases where a degree of uncertaintytriangulation was used. That is, a number of data collectionsurrounds the problem (i.e. very little prior research exists).methods were used to collect evidence. The primary method forEssentially, we tried to understand the phenomena of domaindata collection was interviewing. Five semi-structured interviewsmodeling and object persistence at Volvo IT through thewere conducted with software architects and system analysts tomeanings that people assign to them. The aim was to interpretgain knowledge about object persistence approaches and domainhow software architects and system analysts understand domainmodeling in general. Each interview lasted about one hour. Due todriven design and object persistence, what they view as besttime limitations, interview questions tended to be very focusedpractices and why. This was achieved through a series of semi-and concrete (see Appendix A). Still, an interviewee was allowedstructured interviews (see later in the section). Our interpretationsmaximum reasonable latitude in elaborating. Interview questionswere then used in formulating the Entity Framework guidelines,were refined after each interview to account for new information.which can be understood as the tentative theory behind applyingEach interview was recorded. Subsequently, all interviews werethe EF in DDD. The guidelines represent an initial theory atranscribed and the transcripts were analyzed on the subject of anytheory that must be tested repeatedly to be corroborated orrecurring words or phrases. The transcripts were explicitlydisproved.analyzed according to expected outcomes of the thesis work. No2.1 Context and Subjectsstatistical analysis was performed on data extracted fromThe studied company in this research project was Volvointerviews.Information Technology (referred to as Volvo IT henceforth). TheIn addition to interviews, extensive body of softwarecompany is a wholly-owned subsidiary of AB Volvo (Volvo documentation was reviewed from the software portfolio at VolvoGroup), one of the largest industrial groups in the Nordic region.IT. Important information from the documentation was noted andVolvo IT is the information technology competence center forlater revisited for analysis. This initial study made furtherVolvo Group. It provides software solutions to support industrial interview questions more focused and relevant. Moreover, anprocesses with competencies in Product Lifecycle Management,experiment aimed at evaluating the performance of the EntitySAP solutions, and IT operations. This case study was Framework query execution provided important input to thesiscommissioned by Software Process Improvement (SPI) groupresult. Finally, a number of informal discussions with the seniorwithin Volvo IT, which is responsible for developing and.NET architect also complemented evidence gathered during themaintaining processes and methods for application development.study.The group was exploring a possibility of adopting the EntityFramework as a persistence mechanism in software development2.4 Study Executionprojects that emphasize domain-driven design. Accordingly, theThe case study was performed on Volvo IT premises indevelopment of guidance on adopting the framework is a unit ofGothenburg (Sweden) during the 20-week spring semester period.analysis (case) in this study. To our best knowledge, no previous The study was executed in the following stages:studies have been performed in this area. Thus, the conclusionsStage 1: Several initiation interviews were conducted with thedrawn in this case study could potentially inform critical decisionssenior .NET architect to identify main goals for transitioning toabout incorporating the framework into domain-drivenDDD with the Entity Framework at Volvo IT. The interviews alsodevelopment in a number of similar enterprises. Due to thesought to elicit important requirements that the Entity Framework3 12. guidelines would need to fulfill. The data collected during the multiple sources of information: interviews, documents andinterviews addressed RQ1 and served as the basis for furtherinformal conversations. Moreover, the findings from dataguidelines verification.collection were evaluated by interviewees during a joint EntityFramework workshop.Stage 2: Five interviews with software architects and systemanalysts were performed. The goal of these interviews was toHowever, the construct validity threat to this study still remainsidentify the most common pattern of working with object because we cannot guarantee that during the one-hour workshopmodeling and persistence during software development at the the understandability and the readability of the guidelines couldcompany. Furthermore, this stage sought to elicit specificbe verified with absolute certainty. During the presentation someconcerns that needed to be addressed in adopting the EF. The data of the interviewees deemed the guidelines too abstract in theirobtained from the interviews was augmented by observing one pattern form, while others considered the level of abstractionsoftware architect working with a persistence layer in an actualappropriate. Ultimately, we believe the most reliable way to verifysystem. Besides, considerable amount of data was collectedthe guidelines in this regard would be to test them in a realthrough studying documentation for the Entity Framework and development project. However, we did not have this opportunity.some internal Volvo IT production systems as well as during Still, we believe we managed to curtail this threat to some extentinformal discussions with the senior .NET architect. In this way, by including concrete examples within each guideline.not only RQ2 was addressed, but also enough information wasAnother threat to construct validity relates to the fact that only thegathered to begin creating the EF guidelines.Beta 3 version of the ADO.NET Entity Framework was used inStage 3: Based on the evidence collected during stages 1 and 2 athe performance experiment (see Section 7). Thus, the resultsset of guidelines for adopting Entity Framework in domain-drivenfrom an experiment with the release-to-manufacturing version ofdesign were created. RQ3 was thus partially addressed.the framework could diverge from our results, which wereobtained with the Beta 3 version.Stage 4: The purpose of this final stage was to perform initialevaluation of the guidelines proposed in Stage 3. The objectivewas the verification of understandability and readability of the3. RELATED WORKguidelines. This was achieved through a joint Entity FrameworkThe primary source for domain-driven design principles is Evansworkshop where the researcher and all study subjects discussed[22]. The author introduces a number of important fundamentalthe guidelines. Thus, RQ3 was completely addressed. concepts and guidelines for adopting DDD practices within asoftware development project. However, he does not provide theEventually, by answering all three research sub-questions we were guidelines in the context of any specific tool. Fowler [25] alsoable to address the main research question of the case study. offers a relevant discussion of object-oriented domain models and2.5 Threats to Validity other alternatives to modeling domain logic. Besides, the authorpresents a detailed discussion of object-relational mappingAccording to Yin [48], a case study design needs to satisfy theapproaches. Nilsson [36] offers an interesting discussion offollowing important quality conditions: construct validity, internalimplementing domain object models in C# programmingvalidity, external validity, and reliability. Due to its exploratorylanguage. He considers such issues as building a domain objectnature this case studys design is not exposed to internal validityfactory, creating a repository for object aggregates and mappingthreat. That is, the current case study does not seek to identifydomain objects to relational tables with the NHibernate mappingcausal links in phenomena, which makes internal validity not atool.concern.Still, after an extensive literature review we found no studies ofTo achieve sufficient reliability the case study design adhered tohow the Entity Framework, based on a conceptual data model, canthe two basic principles specified by Yin [48]. First, data be incorporated into domain-driven software development. To ourtriangulation was applied to minimize the risk of bias in databest knowledge, there is no research into how rich domain modelscollected from a single source. Accordingly, we augmented should be mapped and persisted to a relational database via aninterview data with data from software documentation reviewsEntity Data Model (EDM) supplied by the EF. As the reader mayand informal discussions with stakeholders. Second, the study recall, by rich domain models we understand models that describedesign maintained a chain of evidence [48] by following a well- a complex business domain by using a number of advanceddefined multi-stage process (see previous subsection) spanningobject-oriented techniques, such as inheritance and designfrom initial positing of research questions to deriving ultimatepatterns [25]. However, several studies of domain-driven design,case study conclusions. handling persistence and applying object/relational mapping toolsAdmittedly, there exists an external validity threat in that only one in industrial projects exist.company was investigated. This could largely undermine theLandre et al.[30], presenting their experiences from building anpotential for making generalizations beyond the immediate case. oil trading application with an object-based domain model in itsHowever, this threat cannot be minimized to any significant extentcore, describe how Java Data Objects (JDO) - based mappingat the present stage as more research is needed to corroborate or approach was used to persist domain entities. The authors arguedisprove the case study findings in a wider industrial context. that domain-driven design along with a proper object-relationalThere is also a construct validity threat in this case study. The mapping tool generally improved system performance anddanger to construct validity comes from the fact that datareduced the code size relative to some of their existing legacycollection methods and resulting evidence may be biased due toapplications. An important improvement came from incorporatinginvestigator subjectivity [45, 48]. To counteract this we useda Repository domain pattern [22]. According to this pattern allpersistence-related code was encapsulated inside a repository and4 13. the resulting business logic code, oblivious of persistence can be evaluated. The authors also present the results from ainfrastructure, operated only on pure business entities. This in turn qualitative evaluation of existing solutions. Their study includedresulted in cleaner code, which facilitated communication withinsuch tools as object/relational mapping tools, object-orientedthe team. However, it was difficult at first, as authors noted, todatabase systems and orthogonal persistence systems.change the mindset of database-oriented developers to an object-Researchers and practitioners have developed a number oforiented way of formulating JDO queries. The JDO mappingsolutions helping to mitigate or altogether eliminate the object-approach did eventually pay off as developers no longer had torelational impedance mismatch. Some of the proposed solutionsconcern themselves with the minute details of the relationalare discussed below.database schema and instead focus on core business entities. Still,while the authors presented important drivers behind migrating to One solution that completely prevents the mismatch is to usea mapping layer, no meaningful guidelines were offered on how object-oriented database systems (OODBS). OODBS enable a so-mapping tools should be integrated into domain-driven called transparent persistence [36], whereby both persistentdevelopment or what role domain modeling should play in the objects and in-memory objects are accessed in the same way. Thisprocess.is achieved through storing objects directly rather thantransforming them to relational constructs before persisting [49].Wu [47] presents an enterprise system intended to assess humanAs a result only one object-based domain model needs to exist inperformance. The system domain model was generated by the the application, resulting in overall design improvements [49].Entity Object framework3. This framework closely resemblesHowever, predictions of a wide adoption of OODBS did notRepository pattern [22]: it encapsulates all persistence-relatedmaterialize as they have achieved only a 2% share of theissues through object-relational mapping and thus enables a international database market [32]. Relational databases remaindeveloper to work with a pure object-based domain model. Thethe dominant persistence mechanism [15].author claims that the architecture based on the Entity Objectframework effectively decoupled the database from the rest of the Another interesting approach to persistence is orthogonalapplication and improved the overall design since developers no persistence [5, 40]. Orthogonality in this sense considerslonger had to be aware of the intricacies in the relational databasepersistence as merely an aspect of an application. The basic tenetschema. Still, the author fails to examine the framework in the behind orthogonal persistence is the obliviousness of thewider context of domain-driven design and domain modeling.persistence concern. Once persistence has been aspectisized, therest of the application can be built as if no data needs to beA promising approach to domain-driven design is proposed by persisted. The persistence mechanism can be plugged in at a laterPhilippi [38]. The author discusses experiences from developing a time. There have also been some attempts to embed persistencemodel-driven tool that allows visually modeling an object domaincapabilities directly into a programming language [12].model and then automatically generating persistence-related codeand data definition language (DDL) SQL queries. The mappingbetween domain objects and relational tables is specified with a4. THEORETICAL FRAMEWORKwizard tool. Essentially, an application developer specifiesThis section seeks to define important terms actively useddifferenttrade-off criteria, such as maintainability, throughout the thesis report. It contrasts two approaches tounderstandability, which in return generates mappings for a addressing domain logic in enterprise applications. The sectionchosen object-relational tool vendor. The system currentlythen introduces the basic concepts of domain-driven design.supports TopLink. The author also discusses how mappings of Finally, the section delves into the Entity Framework: itsattributes, associations and inheritance hierarchies can be architecture and its basic premise of conceptual dataperformed. He also makes a seminal analysis of differentprogramming.mappings in terms of understandability, maintainability, storage4.1 Structuring domain logicspace and performance. We actively used the results from this Oldfield [37] discusses three types of requirements that anyanalysis in formulating mapping patterns which are a part of theapplication software has to fulfill. First, there are requirementsEntity Framework guidelines. Finally, the author argues that theoriginating from users, which determine systems purpose andstarting point for the automatic generation of object-relationalhow the system is used. These requirements are usually capturedmappings is an application object model a domain model. in Use Cases [10]. Second, there are non-functional requirementsGenerally, the problem of a paradigm schism between object andthat capture quality attributes of a system: reliability, performance,relational models has been a longstanding one [18] and has been security and many others. Finally, there are domain requirements.widely studied [4, 7, 11, 15, 25, 29, 33, 46]. Several patternA domain of a software product is the subject area in which thelanguages have been created, which catalogue best practices inuser applies this product [22]. Domain requirements capturemapping objects to relations [15, 29]. We used a number of theseessential domain concepts, their relationships and important rules.patterns to complement our own mapping patterns, especially Business rules, for example, constrain and control the way awhen it came to mapping the EDM to a relational model.business operates. In this report, we use the term business rulesMoreover, to define the pattern language we consulted [29]. interchangeably with terms like domain logic, business logic orCook and Ibrahim [18] review numerous issues affecting theapplication logic. We also use the terms business object, domainlanguage/database integration and develop these issues into object and business entity interchangeably in this report.criteria against which different solutions to impedance mismatchHistorically, in the object community there have been severalapproaches to organizing and implementing business logic in3applications. Fowler [25] identified three patterns of organizing.NET-based enterprise framework for domain-driven design. Availabledomain logic in enterprise applications: table-based record set at http://neo.sourceforge.net/5 14. (Table Module), procedural (Transaction Script) and domainthe database [4, 11]. In fact, recognizing this limitation inmodel-based (Domain Model). Table Module and Transactionrelational modeling, Peter Chen in 1976 devised the entity-Script patterns are largely database-driven in a sense that the relationship model approach [17] to conceptual data modeling.relational model determines the structuring of domain objects and Domain object models, unlike their relational counterparts, modeltheir relationships. Subsequently, all logic is concentrated in a set conceptual real-world business entities and operate at a higherof heavyweight application services operating on database table-abstraction level.like objects (data containers), instead of actual business entities All business logic in the procedural style resides in the businesswhere they naturally belong. Domain Model (DM) pattern, on thetier within MoneyTransferService. This service performs aother hand, stresses the importance of decoupling the objecttransfer of money assets from one account to another. The servicemodel from the database model and structuring the whole definition executes all business rules (such as overdrafting policy)application around the object-based domain model4 a domain- before crediting and debiting accounts.driven approach [22]. According to this pattern, encapsulating alldomain logic in a set of interconnected business objects (domain Web TierWeb Tier ASPXControllermodel) is a way to manage complexity inherent in mostbusinesses. In the following subsections we contrast TransactionScript and Domain Model patterns for illustrating two distinctapproaches to structuring domain logic. Business Tier4.1.1 Procedural style (Transaction Script)MoneyTransferServiceThe basic premise behind this style is that all application logic isorganized into a set of procedure-like scripts (fat services), each +TransferMoney(in fromAccount, in toAccount, in amount)of which handles a single request from the presentation layer.Normally, a single script is responsible for one business Data Tier-fromAccounttransaction, such as book a hotel room, transfer money from oneAccountaccount to another, etc [25]. Figure 1 illustrates a part of a -accountID * -accountType 1banking application5 built with the Transaction Script pattern.-balance Customer *The most salient characteristic of this design approach is that-customerIDdomainobjects/entities (Account,Customerand-firstNameBankingTransaction -lastName 1-toAccountBankingTransaction) do not encapsulate any business logic per se.-address1 -transactionID -address2 -amountDomain objects in this model represent bare data containers (with-date 1getter/setter fields), which is in a fundamental conflict with the*object-oriented paradigm of encapsulating both data and behavior[23]. In fact, the structure of the database schema largelyMaps one-to-one todetermines the design of these objects. Fowler [23] refers to sucha model as anemic domain model database-driven with noAccount BankingTransactiondomain logic. While there is nothing wrong with a domain modelaccountID transactionIDstructure closely resembling that of a relational model (one-to-one accountType amountmapping), a mechanic derivation of a domain object model from a accountBalancedatedatabase with no regard to the principle of encapsulation could customer_FK fromAccount_FKtoAccount_FKcause problems in later stages of development. Most importantly,this could lead to broken abstractions in the application. Forexample, a real-world entity Order could be split into severalOrder-related tables in the database due to normalizationrequirements. Following the procedural pattern, these tablesCustomercustomerIDwould be one-to-one mapped to domain objects in the data tier.firstNameAs a result, the Order entity will be fragmented over a number oflastNamerelated objects in the object model and the mental model of the address1application will be disrupted. It is necessary to remember that a address2relational model with its mathematical underpinnings may not besuited for modeling real world domains at a high level ofabstraction. It is a logical representation of how data is stored in Figure 1: Part of a banking application built in a procedural style4Essentially, a domain model is a way to express domain requirements byThis design style has some properties that make it attractive forexplicitly capturing essential business concepts, their relationships and building non-sophisticated enterprise applications [25]. First, it isrules in a concrete model.easy to add new functionality by implementing a new transaction5 script. Second, it does not require significant object modelingThis example was inspired by the presentation made by Chrisskills. In fact, some enterprise application frameworks (e.g. J2EERichardson on Improving Application Design with a Rich DomainModel. Available athttp://www.parleys.com/display/PARLEYS/Improving+Application+Design+with+a+Rich+Domain+Model?showComments=true6 15. EJB6) even encourage this style. However, a significantapplication design with the domain model at the core domain-disadvantage of this approach is that it does not scale well todriven design. Next sub-section addresses this approach at length.complex business domains. As more and more functionality isadded, transaction scripts tend to multiply and swell in size. As aresult, the potential for the same business logic to be repeated inThere are a number of benefits to having a domain model at theseveral places becomes more pronounced, which seriouslycore of the application design. Firstly, because the domain modelundermines application maintainability. Another problem with the is decoupled from the relational model, such design reflects thestyle, as we mentioned, is that the resulting object model is largelyreality of business better. Clients to a domain model are able todatabase-driven hence, some adverse implications for operate in terms of real business concepts. Secondly, a domainapplication abstractions.model represents a model of business and its core concepts. These concepts rarely change and are quite stable. Therefore, by4.1.2 Domain Model style encapsulating all business-related functionality in a domainThe Domain Model pattern prescribes offloading all the domainmodel, it becomes possible to reuse the model in a new contextlogic from services (transaction scripts) and encapsulating it (new applications, for example). Finally, as Evans [22] stresses, ainside a domain layer a layer of objects that model the business domain model represents a ubiquitous language a commonarea. Essentially, the business logic is modeled as operations onlanguage shared by domain experts, developers, managers andclasses and spread among a collection of domain objects. See other stakeholders. Ubiquitous language facilitates sharedFigure 2 for the comparison of the two design approaches.understanding of the domain, and, ultimately, leads to better software that is more in line with the user concerns and needs. 4.2 Domain-driven design Evans [22] sees domain-driven design (DDD) as the undercurrent of the object community. The principles of DDD have been known for a long time, yet only recently has the DDD gained increased attention and interest from software developers [22]. The fundamental premise behind the DDD is that most software projects should primarily focus on the problem domain and domain logic. Application design should be based on a domain model. This is achieved by closely mapping domain concepts to software artifacts. DDD should not be viewed as a software development process in its own right. Rather, it is a set of guiding principles, practices and techniques aimed at facilitating software projects dealing with complicated domains. DDD should be applied in the context of an iterative development Figure 2: Transitioning from procedural database-driven process, where developers and domain experts have a closedesign to domain-driven design (adapted from Richardson7)relationship.Most importantly, a domain model is intended to be purelyThe centerpiece of the DDD philosophy is a domain model [22].conceptual: classes in this model directly correspond to real-worldA domain model represents essential knowledge about theobjects. It is, therefore, likely that the domain model will often problem area. It is a tool for overcoming information overload anddiverge from its relational counterpart. To ensure that data can beoverall complexity when a development team attempts to extracttransparently passed between the two potentially diverging modelsdomain knowledge from system users. A domain model is not(due to object-relational impedance mismatch), Fowler [25] just the knowledge in a domain experts head; it is a rigorouslysuggests that a Data Mapper be used. The sole purpose of the Dataorganized and selective abstraction of that knowledge [22] (p.Mapper is to move data between objects and a database while 3).keeping them independent of each other and the mapper itselfFowler [25] offers a relevant discussion of domain models. A[25]. It could be understood as a translator that performs datadomain model captures the business area in which an applicationtransformations as it crosses object-relational boundary. Object-operates. It models essential business entities (domain objects)relational mapping tools emerged as a result of the need for and their intrinsic qualities such as attributes or constraints from aautomatic data translation and mapping of object models to conceptual perspective. But above all, a domain modeldatabase models. To date, a number of commercial (LLBLGenencapsulates all domain logic, which might include business rules,Pro, Apple WebObjects) as well as open sourceconstraints and other important components.(Hibernate/NHibernate as the most popular) solutions exist. Infact, a whole new discipline appeared as a result of pursuingImportantly, a domain model is not necessarily a diagram or some other illustration, rather, it is the notion that a diagram seeks to convey. A diagram can communicate a model, as can more textual6It is notable how its reference architecture encourages Transaction Script representation. However, considering that object-orientation is thinking: Enterprise Java Beans (EJB) implement procedures by largely based on modeling real-life objects, object-oriented operating on an anemic Entity Bean-based model. models (namely, a class diagram) have become a de-facto7See standard for capturing domain knowledge (see Appendix C).http://www.parleys.com/display/PARLEYS/Improving+Application+DeIn a sense that DDD espouses a model as the primary artifact insign+with+a+Rich+Domain+Model?showComments=truesoftware development, it is closely related to model-driven 7 16. Interfacedevelopment (MDD) philosophy. Both methodologies strive to Userreduce complexity inherent in application domains by raising thelevel of abstraction in software construction to a level that iscloser to a problem domain [42]. However, unlike DDD, MDDstresses automatic generation of programs based on correspondingmodels [43]. In this context, DDD does not see the domain modelas a platform for code generation. Rather, the domain model in ApplicationDDD is considered to be a facilitator of a common languageshared by all stakeholders [22]. Moreover, instead of having justone central model (e.g. a domain model in DDD), MDDprescribes producing a number of models targeted at differentabstraction levels [1]. Such models may include computation-independent models (domain models), platform-independent andplatform-specific models [1, 26]. Domain4.2.1 The building blocks of domain-driven designA domain model seeks to bridge the gap between analysis anddesign by addressing concerns belonging to both of the activities.One can find not only familiar business objects/entities in themodel (business analysis model), but also objects representingservices, repositories and factories (design model). Figure 3Infrastructurepresents a navigation map of the DDD concepts.Figure 4: Layered architecture according to DDD (source: Evans [22]) Infrastructure layer provides technical support for all application services. Such technical capabilities can include message sending, persistence for the domain model, etc. Domain layer is the place where the domain model lives. It is responsible for representing business concepts (state) and business rules. Application layer is supposed to be thin: it only orchestrates use case flows (task coordination) and then delegates to behavior-rich domain objects for most domain logic. Finally, the User Interface layer is a regular front-end of the application. It is either a graphical user interface (GUI) through, which users feed commands to a system,Figure 3: A navigation map of the language of domain-drivenor a system interface to which external applications can connectdesign (e.g. a Web service).(source: Evans [22])In the paragraphs to follow, we briefly discuss each of the4.2.1.2 Entitiesbuilding blocks. For a more detailed text the reader is referred toAn entity represents a domain object that is defined not by itsEvans book on domain-driven design [22].attributes, but rather by continuity and identity [22]. Entities usually directly correspond to essential business objects, such as account or customer. Thus, entities are usually persistent: they are4.2.1.1 Layered architecture stored in the database. From database storage comes one of theFrom an architectural viewpoint, a domain model comprises a defining characteristics of an entity: continuity. Continuity meansdistinct layer in an application that encapsulates a set of stable that an entity has to be able to outlive an application run cycle.business object types [44]. In DDD a domain layer constitutes the However, once an application is re-started, it should be possiblecore of the application design and architecture. It is responsible to reconstitute this entity. To differentiate one entity from anotherfor all fundamental business rules. It is in the domain layer that a concept of identity is introduced. Every entity possesses anthe model of the problem area resides. This appears in sharp identity that uniquely identifies it in a set. Accordingly, even ifcontrast with the procedural approach in Transaction Script where two entities have the same attribute values, they are consideredall domain logic is concentrated in the application (service) layer. distinct so long as their identities differ.Figure 4 illustrates the layered architecture to which most DDDapplications adhere: 4.2.1.3 Services Services represent concepts that are not natural to model as entities [22]. Services are responsible for pieces of domain logic 8 17. that cannot be encapsulated in an entity. A service can besubjected to the root. The boundary defines what is inside theconsidered as an interface or an entry point into the domain modelaggregate and what is outside. The defining characteristic of afor external clients. A proper service possesses three importantroot is that outside objects are allowed to hold references only tocharacteristics[22]: 1. the operation a service implements directly the root of an aggregate.relates to a business concept; 2. the service interface is defined in Aggregates play an important role in a domain model. Theyterms of the elements of a domain model (intention-revealingprovide an abstraction for encapsulating references within theinterface); 3. a service operation is stateless.model. For an outsider, a domain model consists only ofAs an example of a good domain service, consider the case aggregates and their roots. Clients of a domain model can onlywhen an application implements a transfer of funds between twohold direct references to aggregate roots. Other non-root objectsbank accounts. The transfer operation directly relates to the should be accessed via traversal. Importantly, should an aggregatebanking domain term funds transfer. Modeling the transfer root be deleted from persistent storage, all aggregate members willoperation on one of the entities (e.g. account) would be somewhat also be removed. Also, when a root is saved, the ensuingundesirable because the operation involves two accounts. Thus, atransaction spans the whole aggregate.funds transfer operation is best factored into a separate domainservice operating on domain entities (see Appendix C). A service4.2.1.5 Factoriescan be directly accessible from the application or a presentation A factory is a mechanism for creating complex aggregates [22].layer.An aggregate, as a rule, has to maintain invariants (constraints). Afactory ensures that an aggregate is produced in a consistent state.4.2.1.4 AggregatesIt makes certain that all entities are initialized and assigned anAn aggregate is a set of related entities that can be treated as aidentity. So instead of directly creating an object from anunit for the purpose of data changes [22]. In a system with aggregate via a constructor, a client requests a specific factory topersistent data storage there must be a scope for a transaction toconstruct an entire aggregate and return a reference to thechange data. Consider a case when a certain number of related aggregate root.entities are loaded from the database into the main memory. Aftermodifying the state of some of the objects a user attempts to save4.2.1.6 Repositorytheir work. A database transaction is spun to maintain data A repository represents all domain objects of a certain type as aconsistency during the save operation. However, should thecollection [22, 25]. Main responsibilities of a repository are:transaction apply only to the saved object or should it also applyquery databases and return (reconstitute) a collection of objects toto its related object(s)? Another issue arises when a deletion of a the client, delete domain objects from persistence storage and alsodomain object occurs. Should the related objects also be deletedadd new objects to persistent storage. It acts as an object-orientedfrom the persistent storage? Essentially, an aggregate addressesapplication programming interface (API) for data, entirelythese issues by identifying a graph of objects that are treated as aencapsulating database access infrastructure. A repositoryunit. Any operation performed on an object within the graph contains all database-related queries and object-relationalautomatically applies to all other graph members (e.g. amapping specifications. It acts as an additional layer of abstractiontransaction). Figure 5 illustrates an aggregate.over the domain layer. Accordingly, through a repository onlyaggregate roots can be reached. Other objects internal to anaggregate are prohibited from access except by traversal from theroot.4.3 The ADO.NET Entity FrameworkMicrosoft Corporation released the beta 3 version of the EntityFramework (EF) in the late 2007 [2]. The fundamental principlebehind the EF is that the logical database schema is not always theright view of the data for a given application. Accordingly, themain goal of the framework is to build a level of abstraction overa relational model. This abstraction is realized with the conceptualdata model which is composed of entities representing real-worldobjects. In this way, a database application can view data asconceptual entities rather than as logical database relations. Byintroducing a conceptual abstraction over a relational store, theEF attempts to isolate the object-oriented application from theunderlying database schema changes. In doing so it is very similarto traditional object-relational mapping tools. However, the EFalso introduces a distinctive feature the Entity Data Model which we discuss in the following subsection. Section 4.3.2presents the comparison of traditional data access with the SQLFigure 5: Aggregate (adapted from Evans [22]) Client and new data access with the Entity Framework.Each aggregate has a root object (Car) and a boundary. The rootis a single specific entity which is considered primary. All other4.3.1 The building blocks of the Entity Frameworkobjects (Wheel, Position and Tire) within an aggregate areFigure 6 illustrates the basic elements of the Entity Framework.9 18. Consisting of conceptual entities and corresponding relationshipsADO.NET Entity Framework the EDM hides the relational model of the database from the rest of the application. It corresponds to a conceptual layer in the EF. The EF performs mapping of a conceptual layer to a logical layer Entity SQL ObjectServicesLINQ to Entities (relational model) by introducing two additional layers below the EDM: mapping specification and storage schema definition. Storage schema definition is essentially a specification of aEntity Clientrelational database model. Mapping specification reconciles the object-relational impedance mismatch by mapping conceptual entities in the EDM to relations (tables) in the storage schema.Entity Framework Metadata Layers 4.3.1.2 Entity client While the concepts of the EDM and mapping may seem abstractCONCEPTUAL Entity Data Model at first, during program execution they are made concrete with a special ADO.NET8 interface EntityClient. Entity client is a data- access provider for the EF, which is also called mapping provider. Entity-to-RelationIt encapsulates and handles database and EDM connections. It isMAPPING mapping specificationvery similar to a regular SQL Client in ADO.NET, which allows applications to connect to relational data sources. However, unlike SQL Client, Entity Client provides access to data in the EDMRelational databaseLOGICALterms. In this case, the EDM acts as a conceptual database similar model to Repository concept from DDD. 4.3.1.3 Entity SQL When an application uses the Entity Framework and its mapping provider to access data, it no longer connects directly to theDatasource database. Rather, the whole application operates in terms of the EDM entities. Therefore, it is no longer possible to use the native database query language for retrieving data. The EF enables Figure 6: Entity Framework architecture (adapted from [4]) querying against the EDM by introducing a query language EF is claimed to largely overcome impedance mismatch problem Entity SQL (eSQL) [4]. The overall structure and syntax of Entityby elevating the level of abstraction in data programming from SQL is very similar to those of the standard SQL (usual SELECT-logical (relational schema) to conceptual [4, 11]. This implies that FROM-WHERE sequence). Unlike the SQL, eSQL introducesthe application can be oblivious of the relational schema by additional features such as support for navigational properties (itaccessing persistent data through an explicit conceptual model is possible to traverse entities instead of using JOIN) and supportcalled Entity Data Model (EDM). EDM abstracts away logical for inheritance.(relational schema) design from the rest of the application byexposing high-level business entities as data containers. In this4.3.1.4 Object Servicesway, persistence layer is decoupled from the application layer,Considering that most applications are written in object-orientedwhich mitigates impedance mismatch problem.languages and thus operate on objects, the EF introduces Object Services feature [4]. The EF includes a tool that, given the EDM4.3.1.1 The Entity Data Modeldefinition, will generate a domain object layer for use in theThe Entity Data Model (EDM) follows the notation of the Entity-application. By using Object Services it is possible to query theRelationship model [17]. The key concepts introduced by theEDM with eSQL and retrieve strongly-typed objects from theEDM are [4]: store. In the same manner, once the application has finished Entity: entities directly correspond to the same concept inworking with objects in memory, it only has to invoke thethe domain-driven design. They are characterized bySaveChanges operation. Subsequently, the mapping provider willcontinuity (persistent) and have a unique identity. Entities inpersist these objects by transforming them into correspondingthe EDM represent conceptual abstractions over the SQL statements to relational database.relational model and, therefore, model exclusively real-lifeobjects. Each entity is an instance of Entity Type (e.g. 4.3.1.5 LINQ to EntitiesEmployee, Order). At runtime entities are grouped into When it comes to querying databases for data, applicationEntity Sets. programmers have to use two languages for this purpose: the query language and the programming language for manipulating Relationship: relationships associate entities to one another. the retrieved data. This not only implies that programmers have toCurrently, the EDM supports three types of relationships:master two distinct languages, but also that queries specified asassociation, containment (entities contained are dependenton the parent entity similar to object composition) and 8inheritance. ADO.NET is a set of software components that can be used by application developers to access data and data services in .NET environment.10 19. string literals are usually ignored by a compiler and, therefore, can 1.void PrintSoftwareProducts(){be validated only during the runtime [16]. To address these issues, 2. using (SqlConnection connection = new3.SqlConnectionMicrosoft introduced the Language-Integrated Query (LINQ) into4. (@"Data Source=itl3df788sqlexpress;its programming languages (C#, Visual Basic). Essentially, LINQ 5. Initial Catalog=EFandSQLClient;Integratedbecame a part of the language definition and its syntax. Therefore, 6.Security=True"))it became possible to perform compile-time validation of queries. 7. {8.connection.Open();The Entity Framework directly supports LINQ and refers to it as 9.SqlCommand cmd =LINQ to Entities query language. LINQ to Entities is an 10. connection.CreateCommand();alternative to eSQL as a query mechanism9. Like eSQL, LINQ to 11. string cmdText =Entities supports complex queries to the EDM which return [email protected]"SELECT name, price, version13.FROM Productstrongly-typed domain objects.14.WHERE version IS NOT NULL15.AND price