Entity Framework Tutorial - Kanjilal Joydip - E-Book

Entity Framework Tutorial E-Book

Joydip Kanjilal

0,0
20,53 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In Detail

The ADO.NET Entity Framework is a new way to build the data access layer of your Windows or web applications. It's an Object Relational Mapping (ORM) technology that makes it easy to tie together the data in your database with the objects in your applications, by abstracting the object model of an application from its relational or logical model.

This clear and concise book gets you started with the Entity Framework and carefully gives you the skills to speed up your application development by constructing a better data access layer. It shows you how to get the most from the ADO.NET Entity Framework to perform CRUD operations with complex data in your applications.

This tutorial starts out with the basics of the Entity Framework, showing plenty of examples to get you started using it in your own code. You will learn how to create an Entity Data Model, and then take this further with Entity types. You will also learn about the Entity Client data provider, learn how to create statements in Entity SQL, and get to grips with ADO.NET Data Services, also known as Project Astoria.

Learn to build a better data access layer with the ADO.NET Entity Framework and ADO.NET Data Services

Approach

This book is written as a tutorial, leading you through examples to illuminate the main theory and get you working with the Entity Framework as quickly as possible.

Who this book is for

This book is for C# developers who want an easier way to create their data access layer. You will need to be comfortable with ADO.NET, but you don't need to know anything about the Entity Framework. Along the way we will create some ASP.NET applications, so being familiar with this will also help.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 176

Veröffentlichungsjahr: 2008

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Entity Framework Tutorial
Credits
About the Author
About the Reviewer
Preface
What This Book Covers
What You Need for This Book
Who This Book is For
Conventions
Reader Feedback
Customer Support
Downloading the Example Code for the Book
Errors
Piracy
Questions
1. Introducing the ADO.NET Entity Framework
What You should Know
Looking Back
What is ADO.NET Entity Framework?
Is It Just Another ORM?
The ADO.NET Entity Framework Architectural Components
The Entity Data Model (EDM)
How is the Entity Data Model Represented?
The Object Model (O-Space)
LINQ to Entities
Entity Client
Entity SQL
Avoiding Complex Joins
The Object Services Layer
ADO.NET Entity Framework—Features and Benefits at a Glance
Installing the Prerequisites
Installing the ADO.NET Entity Framework and Its Tools
Downloading the Software
Installing the Software
Designing the Payroll Database
Summary
Glossary
2. Getting Started
Creating an Entity Data Model
Creating the Payroll Entity Data Model Using the ADO.NET Entity Data Model Designer
Creating the Payroll Data Model Using the EdmGen Tool
The ADO.NET Entity Data Source Control
Implementing Our First Application Using the Entity Framework
Summary
3. Entities, Relationships, and the Entity Data Model
Entities, Entity Types, and Relationships in the ADO.NET Entity Data Model (EDM)
What is an Entity?
Defining Entity Sets in the Entity Data Model
Extending the Existing Entity Types to Create Derived Entity Types
Association Sets, Associations, Containment, and Multiplicity
What are Entity Containers?
Exploring the Payroll Entity Data Model
The Mapping Details Window
The Entity Model Browser
The Entity Data Model Layers
The CSDL Schema
The SSDL Schema
The MSL Schema
Summary
4. Working with Stored Procedures in the Entity Data Model
Mapping Stored Procedures to Functions in the EDM
Mapping Create, Update, and Delete Functions to Entities in the EDM
Mapping the Association Sets Consistently
Mapping Stored Procedures with No Entity Set
Using Stored Procedures
Mapping Stored Procedures that Return Custom Entity Types
Summary
5. Working with Entity Client and Entity SQL
An Overview of the Entity SQL Language
From Transact SQL (T-SQL) to Entity SQL (E-SQL)
Why Entity SQL When I Already have LINQ to Entities?
Features of Entity SQL
Operators in Entity SQL
Arithmetic Operators
Comparison Operators
Logical Operators
Reference Operators
Type Operators
Set Operators
Operator Precedence
Expressions in Entity SQL
Query Expressions in Entity SQL
Identifiers, Variables, Parameters, and Types in Entity SQL
Row
Collection
Reference
Canonical Functions in Entity SQL
Mathematical Functions
Aggregate Functions
String Functions
Bitwise Functions
Date and Time Functions
Data Paging Using Entity SQL
Working with the ADO.NET Entity Client
Let's Get into Action
Building the Connection String
Creating an Entity Connection
Opening the Connection
Executing Queries Using the Entity Command
Closing the Connection
Other Operations with Entity SQL
Inserting a Record Using Entity SQL
Inserting a Record with a Foreign Key Constraint
Retrieving Native SQL from EntityCommand
Transaction Management in Entity SQL
Summary
6. Working with LINQ to Entities
Introducing LINQ
Why LINQ?
Understanding the LINQ Architecture
LINQ to XML
LINQ to SQL
LINQ to Objects
LINQ to Entities
Querying Data Using LINQ to Entities
LINQ to Entities and Entity Framework
Differences between LINQ to Entities and LINQ to SQL
Operators in LINQ
Aggregation
Projections
Ordering
Quantifiers
Restriction
Conversion
Element
Set
Querying Data Using LINQ
Expressions in LINQ to Entities
Constant Expressions
Comparison Expressions
Initializing Expressions
Null Comparisons
Navigation Properties
Immediate and Deferred Query Execution
Improving Performance with Compiled Queries
Summary
7. Working with the Object Services Layer
What are Object Services?
Features at a Glance
A Quick Look at the ObjectContext Class in our Payroll EDM
Querying Data as in-Memory Objects
Adding, Modifying, and Deleting Objects
Attaching and Detaching Objects to and from the Object Context
Serializing and De-Serializing Entity Instances
Change Tracking and Identity Resolution Using ObjectContext
Implementing a Sample Application
Creating the Form
Implementing a Custom DataContext
How is This Accomplished?
Updating an Employee Record
Handling Concurrency Conflicts
Inheritance in the Entity Framework
Table per Hierarchy
Table per Type
Table per Concrete Type
Implementing Complex Types in the EDM
Summary
8. Introducing ADO.NET Data Services
Introducing ADO.NET Data Services
How Do ADO.NET Data Services and Web Services Differ?
What is Representational State Transfer (REST)?
Why Use ADO.NET Data Services?
Features at a Glance
Prerequisites
Exposing Data as a Service Using ADO.NET Data Services
Creating an ADO.NET Data Service
Using a Relational Database as the Data Source
Using Data Sources Other Than a Relational Database
Understanding the System.Services.Data Namespace
Restricting Access to Resources
Working with the ADO.NET Data Service Client Library
Generating the Client-Side Entity Classes
Inserting a Record
Updating a Record
Deleting a Record
Consuming an ADO.NET Data Service Using LINQ
Exposing a Stored Procedure as a URI
Handling Exceptions in ADO.NET Data Services
Batching ADO.NET Data Services Requests to Improve Performance
Debugging Your Data Service
References
Summary
Index

Entity Framework Tutorial

William Rice

Joydip Kanjilal

Entity Framework Tutorial

Copyright © 2008 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: October 2008

Production Reference: 1201008

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847195-22-7

www.packtpub.com

Cover Image by Vinayak Chittar (<[email protected]>)

Credits

Author

Joydip Kanjilal

Reviewers

Bogdan Brinzarea-Iamandi

Stefan Turalski

Senior Acquisition Editor

Douglas Paterson

Development Editor

Ved Prakash Jha

Technical Editor

Ajay Shanker

Editorial Team Leader

Mithil Kulkarni

Project Manager

Abhijeet Deobhakta

Project Coordinator

Lata Basantani

Indexer

Monica Ajmera

Proofreader

Joel T. Johnson

Production Coordinator

Aparna Bhagat

Cover Work

Aparna Bhagat

About the Author

Joydip Kanjilal is a Microsoft MVP in ASP.NET. He has over 12 years of industry experience in IT with more than 6 years in Microsoft .NET and its related technologies. He has authored many articles for some of the most reputable sites like, www.asptoday.com, www.devx.com, www.aspalliance.com, www.aspnetpro.com, www.sql-server-performance.com, www.sswug.com, etc. Several of these articles have been featured at www.asp.net —Microsoft's Official Site on ASP.NET. Joydip was also a community credit winner at www.community-credit.com a number of times.

He is currently working as a Senior Consultant in a reputable company in Hyderabad, INDIA. He has years of experience in designing and architecting solutions for various domains. His technical strengths include C, C++, VC++, Java, C#, Microsoft .NET, Ajax, Design Patterns, SQL Server, Operating Systems, and Computer Architecture. Joydip blogs at http://aspadvice.com/blogs/joydip and spends most of his time reading books, blogs, and writing books and articles. His hobbies include watching cricket and soccer and playing chess.

Writing a book is always a rewarding experience. My special thanks to Douglas Paterson for providing me the opportunity to author this book—turning this idea into a reality. I am also thankful to the entire Packt team for their support.

I am also thankful to Abhishek Kant (Microsoft), Steve Smith (AspAlliance), Russell Jones(DevX), Steve Jones(SSWUG), Jude Kelly (SQL Server Performance), and Anand Narayaswamy (AspAlliance) for their inspiration and support. My heartiest thanks to my friends Tilak and Vinod for their continued encouragement.

My deepest respects and gratitude to my parents for their love, blessings, and encouragement. My thanks to my other family members too, for their support, and to little Jini in particular, for her continued inspiration and love.

Thank you all so much!

About the Reviewer

Bogdan Brinzarea-Iamandi has a strong background in Computer Science holding a Master and Bachelor Degree at the Automatic Control and Computers Faculty of the Politehnica University of Bucharest, Romania. He also holds an Auditor diploma at the Computer Science department at Ecole Polytechnique, Paris, France. His main interests cover a wide area from embedded programming, distributed and mobile computing, and new web technologies.

Currently, he is employed as Supervisor within the team of Alternative Channels Sector of the IT Division in Banca Romaneasca, a Member of the National Bank of Greece. He is Project Manager for Internet Banking and he coordinates other projects related to new technologies and applications to be implemented within the banking area.

Bogdan is also the author of two AJAX books, the popular AJAX and PHP: Building Responsive Web Applications and Microsoft AJAX Library Essentials, also by Packt.

Preface

The ADO.NET Entity Framework, the next generation of Microsoft's data access technology, is an extended Object Relational Mapping (ORM) technology that makes it easy to tie together the data in your database with the objects in your applications. This is done by abstracting the object model of an application from its relational or logical model. It is an extended ORM in the sense that it provides many additional features over an ORM. Some of these features are:

Entity Inheritance and CompositionIdentity Resolution and Change TrackingLINQ SupportThe Object Service Layer

This book is a clear and concise guide to the ADO.NET Entity Framework. Packed with plentiful code examples, this book helps you to learn the ADO.NET Entity Framework and ADO.NET Data Services and build a better data access layer for your application.

What This Book Covers

Chapter 1 is an introduction to the basics of the ADO.NET Entity Framework (EF), its usefulness, its features, and the benefits.

Chapter 2 discusses how you can get started with EF, create an Entity Data Model (EDM), and write a program to query data.

Chapter 3 gives a detailed explanation of entities, relationships, and each of the sections of the EDM.

Chapter 4 provides a sample application that illustrates how to perform CRUD operations against the EDM.

Chapter 5 discusses the Entity SQL query language and how to work with the Entity Client provider.

Chapter 6 includes a detailed discussion on LINQ to Entities with many code examples.

Chapter 7 provides a detailed discussion on the Object Services Layer and its helpful and useful features.

Chapter 8 provides an introduction to ADO.NET Data Services and how it can be used with the EDM to perform CRUD operations.

What You Need for This Book

To learn the concepts covered in this book, the reader should have a proper understanding and working knowledge of the following:

ADO.NETASP.NETC#

To execute the code samples in this book, the following technologies should be installed in your system:

Visual Studio 2008Visual Studio 2008 SP1SQL Server 2005Windows XP/Vista/2003 or higher

Who This Book is For

This book is for C# developers who want an easier way to create their data access layer. You will need to be comfortable with ADO.NET, but you do not need to know anything about the Entity Framework. Along the way we will create some ASP.NET applications, so familiarity with this will be helpful.

Conventions

In this book, you will find various styles of text that help distinguish between different kinds of information. Let's look at some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows:

"We can include other contexts through the use of the include directive."

A block of code will be set as follows:

<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" /> <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />

When we wish to draw your attention to a particular part of a code block, the relevant lines or items will be made bold. Note that last two lines of the following code sample:

<FunctionImport Name="DeleteEmployee"> <Parameter Name="EmployeeID" Mode="In" Type="Int32" /> <Parameter Name="DepartmentID" Mode="In" Type="Int32" /> <Parameter Name="DesignationID" Mode="In" Type="Int32" />

Any command-line input and output will be written as follows:

edmgen /mode:fullgeneration /c:"Data Source=.;Initial Catalog=Payroll;User ID=sa;Password=joydip1@3;" /p:Payroll

New terms and important words are introduced in a bold-type font. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: "clicking the Next button moves you to the next screen".

Note

Important notes appear in a box like this with the Notes icon on the left..

Note

Tips and tricks appear like this with the Tips icon on the left.

Reader Feedback

Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply drop an email to <[email protected]>, making sure to mention the book title in the subject line of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer Support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the Example Code for the Book

Visit http://www.packtpub.com/files/code/5227_Code.zip to directly download the example code.

The downloadable files contain instructions on how to use them.

Errors

Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errors, report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errors. Once your errors are verified, your submission will be accepted and the errata added to the list of existing errors. The existing errors can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide the location address or website name immediately so we can pursue a remedy.

Please contact us at <[email protected]>with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]>if you have a problem or question with some aspect of this book. We will do our best to address these questions and problems.

Chapter 1. Introducing the ADO.NET Entity Framework

The ADO.NET Entity Framework is an extended Object Relational Mapping (ORM) technology from Microsoft that abstracts the object model of an application from its relational or logical model. That is, it isolates the object model from the way the data is actually represented in the relational store. This framework makes the conceptual model real by using an extended entity relationship model called the ADO.NET Entity Data Model.

This chapter gives you an introduction to the ADO.NET Entity Framework and also equips you with a brief understanding of the related terminologies. We will revisit each of the Entity Framework architectural components as we progress through this book. Our journey of the ADO.NET Entity Framework has just begun!

In this chapter, we will cover the following points:

An overview of the ADO.NET Entity FrameworkThe ADO.NET Entity Framework Architectural ComponentsFeatures and benefits of the ADO.NET Entity FrameworkInstalling the ADO.NET Entity Framework

But, before we delve deep into this amazing technology from Microsoft, let's take a quick look at the prerequisites for learning the concepts covered in this book.

What You should Know

To learn the concepts covered in this book, the reader should have a basic understanding of the following:

Programming using ADO.NETC#Working with ASP.NET Web ApplicationsSQL Server

Looking Back

Any application has two perspectives. They are the Data Model and the Object Model. While the Data Model defines the way the data is defined and stored, the Object Model defines how the same data will be represented to the user in the presentation layer or, is exposed to the other layers of the application. The Data Model of the application usually deals with the storage and retrieval of the application's data to and from the relational store.

The relational store is used for data persistence, consistency, concurrency, and security. It contains the application's data and typically comprises of a set of tables, views, functions, procedures, and the relationships. You typically use T-SQL to query against the relational store which returns result sets that contains columns and rows of data.

However, the data returned doesn't necessarily match with the application's object oriented programming model. Usually, we don't use the data returned in the same form in which it is returned from the relational store. We write the necessary code to transform the data returned from the relational store to business objects in the data access layer of the application. Similarly, you need into write code to transform your application's business objects into a form that can be persisted into your relational store. But, what if the schema of the underlying relational store changes?

To bridge this apparent mismatch between the data and the object models, ORM tools have evolved. They are used to reduce the code required to transform your application's business objects into a form that can be persisted into the relational store and vice-versa.

What is ADO.NET Entity Framework?

The ADO.NET Entity Framework is a type of ORM. It is a development platform that provides a layer of abstraction on top of the relational or logical model. In doing so, it isolates the object model of the application from the way the data is actually stored in the relational store. Developers can use the ADO.NET Entity Framework to program against an object model rather than the logical or relationship model.

This level of abstraction is achieved using the Entity Data Model (EDM)—an extended Entity Relationship Model. The EDM reduces the dependency of your domain object model on the database schema of the data store in use. We will discuss more on this topic later in this chapter.

Developers can use the ADO.NET Entity Framework to work with domain specific properties such as employee name employee address, contact details, etc, without having to be concerned with how the actual data is stored and represented in the underlying data store. The framework can take care of the necessary translations to either retrieve data from your data store, or, perform inserts, updates, and deletes.

Is It Just Another ORM?

The ADO.NET Entity Framework is an extended ORM technology from Microsoft. We say it is an extended ORM because it has many additional features compared to a typical ORM. ORMs often use metadata and factory classes to retrieve data or collections of data. On the contrary, using the Entity Framework, you can easily map your data to be accessible in a relational representation in the database to objects, no matter how the mapping is implemented. You can expose different data views to your application without having to change your relational schema. In essence, this allows the applications to have their own view of the data. The applications can even reuse the same views of data amongst themselves.

The major difference between the ADO.NET Entity Framework and ORM tools is in the Entity Data Model and the former's ability to query data using strongly typed LINQ. You can even use Entity SQL, a T-SQL like query language for querying the Entity Data Model, to execute dynamic queries. In addition to what a typical ORM framework provides, the ADO.NET Entity Framework provides and supports entity inheritance, entity composition, and a flexible, loosely coupled three tiered model consisting of the conceptual model, the mapping layer, and the storage model.

The ADO.NET Entity Framework enables you to even extend the existing schema. In other words, you can extend the generated entity classes to create your own custom entity classes. You can define relationships of any kind such as one-to-one, one-to-many, and even many-to-many. So, isn't it a better ORM?

The ADO.NET Entity Framework Architectural Components

The ADO.NET Entity Framework is comprised of the following components:

The Entity Data ModelLINQ to EntitiesEntity ClientEntity SQLThe Object Services Layer

The following figure illustrates the layers of the ADO.NET Entity Framework and how they are related to each other: