intro to entity framework

of 49 /49
Intro to Entity Framework A Reconnaissance (No Driving Yet) Tom Perkins

Author: benoit

Post on 24-Feb-2016




1 download

Embed Size (px)


Intro to Entity Framework. A Reconnaissance (No Driving Yet) Tom Perkins. Objectives. Last Session: We created a small Entity Framework application step-by-step and displayed data in a GridView from a database. This Session: We’ll again create a small Entity Framework application. - PowerPoint PPT Presentation


Slide 1

Intro to Entity FrameworkA Reconnaissance(No Driving Yet)Tom Perkins1ObjectivesLast Session: We created a small Entity Framework application step-by-step and displayed data in a GridView from a database.This Session: Well again create a small Entity Framework application.Well look at the components in more detail for the purpose of gaining familiarity with what the Framework produces.Work along or watch!

2A Different Programming PerspectiveApplicationEntity DataModel(EDM)Data StoreDeveloperbridgeFocus on business objectsFocus on tables, stored Procedures, views, etc.3EDM is a conceptEntity Data Model(EDM)Implemented as:EDMX FileDesign timeRun time3 XML Files4XML FilesEntire ModelEntity Data Model SchemaMappingsDatabase Objects Schema*.CSDL*.MSL*.SSDL*.EDMXDesign TimeRun TimeCompile5What Entity Framework DoesGenerates classes from modelUpdates classes as model changesHandles database connectivityQuerying done on model, not databaseTranslates queries into database queriesTracks changes to objects in the modelHandles updates to the database6Build a simple EDMSample database, ProgrammingEFDB12 tables, one view, some stored proceduresCreate a new Console ApplicationIn VS2010, File | New | ProjectSelect Console Application7

Name: Chapter2ConsoleAppLocation: (use default)Solution: ProgrammingEntityFramework8

Click OK9

Right-click on Chapter2ConsoleApp in the Solution ExplorerAdd | New Item10

Select ADO.NET Entity Data Model from the Templates list | Add11

Select Generate from database | Next12

Make sure your local SQL Server is activeSet up a new connection if necessaryChange the App.Config settings name to Sample Entities | Next13

Select Tables, Views | Change Model Namespace to SampleModel | Finish14

New model appears. Note Model1.edmx file. To display the model at any time, double-click on the Model1.edmx file in the Solution Explorer.15The designer window


Gives a graphical view of the EDM and its members. Contact Entity, Address Entity, and vOfficeAddressEntity 2 from DB Tables, one from View connecting line One-to-Many relationship associations Scalar properties (ContactID, FirstName, etc) Navigation properties (Addresses, Contact) Addresses property enables navigation from Contact Entity to set of Addresses related to that contactMultiplicity options:1 (one); * (many); 0..1 (Zero or one) shipper orders may be a 0..1 to * (order may not have a shipper assigned)17Using the Properties WindowA logical group of entities entity containerClick in the white space of the Designer Window, then look at the Properties window.

You can modify the Entity Container Name and the Namespace You can set whether to pluralize new objects or not18The Properties of an EntityClick on the Contact Entity

Entity name: Contact db table Entity Set Name pluralized Entity names should be singular

Entity set a container for entities of a single type 19The Properties of an Entity PropertyClick on Contacts FirstName property

FirstName is a non-nullable string with a maximum length of 50 characters, variable. It is not the Entity key.

The framework does not perform validation of the Max Length, Unicode, and Fixed Length properties. These properties are ignored. 20The raw format of the model-- xml

supporting metadata

21XML FilesEntire ModelEntity Data Model SchemaMappingsDatabase Objects Schema*.CSDL*.MSL*.SSDL*.EDMXDesign TimeRun TimeCompile22Supporting MetadataSectionsConceptualModelsStorageModels (db schema)MappingsLast 2 tell how to translate between conceptual model and actual data storeMapping translates entities and properties (conceptual model) to tables and columns (StorageModel)Physical files stored in project assembly at compile time (you wont see them).23The Model BrowserRight-click on the design surfaceChoose Model Browser from the context menu.Gives another view of the metadata.

24Raw XMLOnly a portion of the model is visible in the Designer.View complete model in XML form.To see the raw format of the model:In Solution ExplorerRight-click on Model1.edmx fileOn context menuSelect Open WithChoose XML EditorClick OK(Only one view of the model at a time is allowed click OK to close the Design View of the model when prompted.)

25Raw XML in the Designer

26Model with Sections CollapsedTo collapse the modelRight-click on XMLChoose OutliningToggle All OutliningExpand nodes to get the main sections of the model:

27CSDL: The Conceptual SchemaIf a line loses its hard returns, Highlight the lineFrom VS Menu, select Edit | Advanced | Format Selection to format the lineIn ConceptualModels section, Click on + icons to expose the Schema and EntityContainer28Expanded Schema and Entity Container nodes

The above XML is the source of the graphical display we saw in the Designer.29Model Elements Well ExamineEntity ContainerEntity SetEntity TypeThe Key ElementProperty ElementsAssociationsNavigation Property30The Entity ContainerName: Defaults from model nameChange in models Property WindowWrapper for Entity Sets and Association SetsExposes Entity SetsYou write queries against these

31The Entity ContainerQUERYEntity Container

ContactsAddressesContact ObjectContact ObjectContact ObjectAddress ObjectAddress ObjectLazyLoading Annotation used as directions for generation of code32The Entity SetGives access to individual entities when querying against modelExample: find some entities in the Contact EntitySet returns some Contact Entity TypesEntity Type: Strongly Typed Name for Entity

33The Entity Type

Key element: Identity key for entity; may be compositetracks entity, helps perform updates and refreshes, very important34Property ElementsCant have XML and Designer open at the same timeClose XML view, double-click .edmx file to view an elements propertiesNot all propertes appear in XML , but do appear in Properties windowCurrency mode, default value, Getter, SetterFacets are used to describe properties

35AssociationDefines relationships between entity typesDescribes end points of relationship and multiplicity (1, 0..1,*)Cascade if Contact is deleted, delete associated AddressesLets look at the view in the Designer Close the XML and double-click on the Model1.edmx in the Solution Explorer.

36FK_Address_Contact AssociationDefines relationships between entities Contact and AddressFocuses on endpointsEnd1 ContactAssigned role ContactAlso name that can be used in model to point to this endMultiplicity (only one Contact)Navigation other end of associationCascade delete addresses if contact is deletedEnd2Role AddressMultiplicity many addresses per contactAssociation Set may be more than one per entity

37Referential ConstraintFor Foreign KeysShows dependency between related entitiesEvery Address must have a ContactUsed to maintain integrity of database

38Address_Contact Navigation PropertyShows how to navigate to associated entityAssociation how to navigate to associated entity (or entities)From Role, To Role navigate from Address to ContactMultiplicity returns 1 Contact object

39Contact.Addresses NavigationThis Navigation Property returns a collection of addressesNo address for Contact, collection will be emptyType is a special EntityCollection, not type implementing System.Collections.ICollection (not interchangeable)

40This CDSLSimple modelConceptual Layer mirrors the database schemaCustomizing the model (later) gives real power to Entity Framework41Ssdl (Storagemodel section)42Expanded StorageModels Section

43StorageModels SectionProvides a description of the data store (database)Tables called Type, Columns called PropertyStore is in Namespace to minimize confusionProviderManifestToken version of SQL ServerYou must modify manually if switching to SQL Server 2005Entity container derived from db nameEntity Type name of table Property types SQL Server data typesIdentity column StoreGeneratedPattern=Identity identity value generated by db when row is inserted, will not changeOther optionsComputed values generatedNone - default

44Msl: Mapping from conceptual Model to storage (and Back)45MSL: Mappings SectionLogically between concept and storage modelsMaps entity properties back to tables and columns of data storeEnables further customization of modelUse the Mapping Details Window(Close XML view) Open Designer (dbl-clk on .edmx)Right Click on Contact EntitySelect Table Mapping46Mapping Details WindowMaps Contact entity to Contact tableMaps to Contact Contact table in SSDLHere, one to one relationship can be customizedWhen you create mappings, wizard matches names for youNote SQL data types

47Database Views: vOfficeAddressNote: DefiningQuery

48SummaryIntroduced you to EDM and design toolsCreated an EDMLooked under the hoodRaw XMLMappingsEnough to get started with QueryingStay tuned for more exciting developments49