intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Pro Entity Framework 4.0 - Apress_1

Chia sẻ: Thao Thao | Ngày: | Loại File: PDF | Số trang:26

62
lượt xem
5
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Nhà thiết kế là công cụ cho phép bạn làm việc với EDM và cung cấp cho các nhà phát triển chức năng cần để tạo, chỉnh sửa và cập nhật các EDM. Thiết kế bao gồm một số thành phần để hỗ trợ bạn trong việc thiết kế và chỉnh sửa mô hình khái niệm của bạn.

Chủ đề:
Lưu

Nội dung Text: Pro Entity Framework 4.0 - Apress_1

  1. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT The Designer is the tool that allows you to work with the EDM and provides the functionality developers need to create, modify, and update the EDM. The Designer consists of several components to assist you in designing and editing your conceptual model. Figure 3-2 shows the different components, including the following: Designer surface: A visual surface for creating and modifying the conceptual • model. Mapping Details window: The location where mappings are created or modified. • The window is discussed later in the chapter. Toolbox: Contains controls that can be used to create entities, associations, and • inheritance relationships. Model Browser window: Provides a view of the conceptual model and the • associated storage model. Model Browser Window The Model Browser window provides a tree view of the conceptual and storage models that are defined in the EDM (specifically, the .edmx). The information in this window is organized by the type of information contained within the window, as shown in Figure 3-2. The first node displays the information found in the conceptual model, such as entities and associations. The second node displays the storage model components, i.e., those components of the database that have been imported into the model, such as tables, views, and stored procedures. Within the Model Browser window you can Locate an entity on the Designer surface by right-clicking the entity and selecting • Show in Designer from the context menu Delete objects from the storage model, including stored procedures, tables, and • views Create function imports from stored procedures by right-clicking on a stored • procedure and selecting Add Function Import from the context menu Update the model from the database • As you select items in the Model Browser window, these items become the active object in the Properties and Mapping windows, making it easy to modify and work with EDM objects. 37
  2. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Figure 3-2. Designer surface and windows Mapping Details Window The Mapping Details window provides an interface enabling you to view and edit the physical mappings between the storage and conceptual models. Through this window you can view and modify the mappings for the tables and views as well as map entities to functions (stored procedures). When an entity is selected in the Designer, the Mapping Details window shows the mapping between the entity properties and the table column in the storage model. For example, in Figure 3-2 you can see the Person entity is selected in the Designer as well as the Mapping Details window showing the mapping between the table columns and the properties of the Person entity. Within this window you can change the individual property mappings or assign imported stored procedures as functions to perform Insert, Update, and Delete operations. With an understanding of the different windows in the Designer, let’s move on and discuss the different components in the EDM Designer itself. Entities To understand the Entity Framework and how entities work, there are a few concepts that you should know: Entity type: This represents a particular type of data, such as Employee, Order, or • Product. Entity types are highly structured records with a key. Entity set: This is a logical container for entities of a single type. • 38
  3. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Entities, therefore, are instances of entity types, and entities can be grouped into entity sets. The model in Figure 3-3 illustrates this concept, which includes three entity types (SalesPerson, SalesOrderHeader, and SalesOrderDetail), two entity sets (SalesPerson and SalesOrder), and relationships between the three entity types. Figure 3-3. Entity and EntitySets With the explicit concept of entities and relationships, developers can now describe schemas more precisely by using entities to provide the formal design for the details of a data structure. In other words, the formal design should specify how an application will encapsulate the different types and kinds of data in a logical structure. The EDM model we created earlier came from the AdventureWorks database, which contains Employees, Products, Sales, and more. Each of these represents a data structure and entities are the formal specifications of the details of those structures. An Order type, for example, contains details such as salesperson, order date, and quantity. A SalesPerson type could contain name, address, and other pertinent information. The EDM represents a logical connection between the SalesPerson and the Order as a relationship, or association. You’ll also notice that the entity set is defined in the properties of the entity itself. For example, Figure 3-4 shows the Employee entity selected with the Properties page opened showing the properties for that entity. One of the properties of the entity is the Entity Set Name. In this example the property takes on the plural version of the entity name, in this case, Employees. This property is editable, and as such allows you to change the entity set name and add multiple entities to the same entity set. Figure 3-4. Entity properties 39
  4. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Scalar Properties Entities are made up of properties. Scalar properties are properties whose values are physically and literally contained within the entity itself. As you saw earlier, you can modify the display of the entity to also show the scalar property data type, also shown in Figure 3-5. Also shown in the figure are the properties of a selected scalar property, including properties such as whether the property can be null or if the property is an entity key. String scalar properties include additional properties that define string length. Figure 3-5. Scalar properties You should also notice a property called StoreGeneratedPattern. This property is used to determine if the corresponding column in the database will be auto-generated during insert and update operations. This property is applied to all scalar properties. Additional properties can be added to entities by right-clicking on the entity and selecting Add ➤ Scalar Property from the context menu, shown in Figure 3-6. Figure 3-6. Adding a scalar property You can then define the data type and other properties of the new scalar property. Complex Types Complex types are not new to the Entity Framework 4.0. They existed in 3.5, but you could not create them via the Designer—you had to create them manually. Creating them manually meant that you had to go into the CSDL (Conceptual Schema) and add the necessary XML to create the complex type. The problem with this is that once you created your complex type, you could not open the EDM Designer anymore because the Designer didn’t support complex types. 40
  5. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT With the Entity Framework 4.0, the process of manually creating the complex type is gone. With EF 4.0 you now have the ability to add complex types via the Designer. Before we walk through how to create them, let’s first back the bus up and discuss what they are. Complex Types Defined Complex types provide a handy mechanism for storing and encapsulating properties related to one or more entities. For example, you may have more than one entity that needs to store phone and email information. Complex types can also be used to add additional structure to your entities. Regardless of how you use them, they are very useful. As you will see shortly, complex types are made up of scalar properties as well as additional complex types. Complex types in EF 4.0 are anything but complex in the sense of what it takes to create one. Complex types are types, meaning that you can instantiate them outside of the parent entity. Yet as such they still provide the ability to navigate to them through the related entity or entities. Let’s take a look at how to create them and how they work. Creating a Complex Type Creating a complex type is quite easy. Open the Model Browser window and expand the top node (the conceptual model node). Within that node is a complex types node, shown in Figure 3-7. The complex types node will contain all the complex types for your model. Complex types can be added, deleted, and modified directly through the Model Browser. As you will see shortly, creating and defining complex types are quite easy to do. Figure 3-7. Model Browser To add a new complex type, right-click on the complex type node and select Create Complex Type from the context menu, as shown in Figure 3-8. This will create a complex type with a default name of ComplexType1. You can rename the complex type by right-clicking the complex type and selecting Rename from the context menu. I renamed my complex type to AddntlContactInfo. 41
  6. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Figure 3-8. Create complex type At this point the complex type is useless because we have not defined any properties. To add properties to the complex type, right-click in the complex type and select Add ➤ Scalar Property, then select the data type of the scalar property you want to create. You can see this in Figure 3-9. As you can see, you have the same data types for complex type scalar properties as you do with regular entity scalar properties. And this should be no surprise because a complex type is simply an extension of your entity or entities. Figure 3-9. Adding scalar properties to the complex type For this example, I added three scalar properties called Active, CellPhone, and EmailAddress, which you can see in Figure 3-10. CellPhone and EmailAddress are type String while Active is type Byte. If you have followed along, congratulations—you have created your first complex type. 42
  7. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Figure 3-10. Finished complex type The next step is to add it to our desired entity. Going back to the EDM, let’s add it to the Contact entity. Adding a complex type is just like adding a scalar property to an entity. Right-click on the entity you want to add the complex type to and select Add ➤ Complex Property from the context menu, as shown in Figure 3-11. Figure 3-11. Adding the complex type to the entity You should now have a complex property added to the entity with a default name of ComplexProperty, shown in Figure 3-12. It would be wise to rename this new complex property something more meaningful. 43
  8. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Figure 3-12. Entity with complex type property Even though you have added a complex property to the entity, you haven’t told it which complex type you want this property based on. This is very easy to do. With the new complex property highlighted, you can either right-click the complex property and select Properties from the context menu, or you can simply open the Properties window. In either case, you will be presented with the properties for the complex property, shown in Figure 3-13. The complex property has a type property, which lists all the complex types defined. Simply expand the drop-down and select the complex type (in this case there is only one) that you want your new complex property based on. Figure 3-13. Setting the type property 44
  9. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Voila, you’re done! You have successfully created and implemented a complex type. Querying this new complex property is as simple as navigating to it from the Contact entity, as follows: Contact.AddntlContactInfo.EmailAddress Throughout this exercise we used the terms complex type and complex property. These terms are not interchangeable. As we have discussed, complex types are made up of scalar properties and other complex types. A complex property is what is added to an entity and based on the complex type. Foreign Keys and Relationships (Associations) As you become familiar with the Entity Framework and the EDM, you’ll find a definite appreciation for how the EF creates associations. Creating the associations is not trivial, and the engine follows specific DDL rules to generate each association. In an EDM, relationships look much like logical relationships at the database schema level and therefore are logical connections between entities. Each entity that participates in an association is called an end. Each end has a role attribute that names and describes each end of the association logically (or in other words, specifies the entities related by the association). Associations have what is called a multiplicity attribute, which specifies the number of instances that each end can take part in the association. For example, Figure 3-14 shows properties of the association (relationship) between the Employee and Person entities. These properties define the association, which include all of the aspects discussed previously. In this example, the roles are the Employee and Person entities, and it is a one-to-many relationship. Although denoted by “0..1” (which means “zero or one”) this can be misinterpreted. This simply means that one Person might have multiple Employee roles, but only one employee can be related to a single Person. A better explanation might be taken from Figure 3-3, a few pages earlier. A salesperson can have multiple sales (in the SalesOrderHeader table), but only one sale can be related to a single salesperson. The OnDelete properties specify an action to be taken when an entity on the corresponding end is deleted. In database terms, this is called “cascading deletes” and provides a way to delete a child record when the parent record is deleted, preventing what are called “orphaned” child records. Figure 3-14. Association properties 45
  10. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT In this example, every Employee must be related to a corresponding Person. Person and Employee are logically related but they exist as independent entities. As such, it is possible to have a Person without an associated Employee, but not possible to have an Employee without an associated Person. This is the “zero or one” part. Table 3-1 describes those association generation rules. Table 3-1. Rules for Generating Associations Relationship (Association) Type Generation Rule One-to-many (1:*) Columns are added to the table that corresponds to the entity type on the 0..1 or * end of the association. The added columns have foreign key constraints that reference the primary key or the table that corresponds to the entity type on the other end of the association. One-to-one (1:1) Columns are added to one of the tables that corresponds to entity types on the ends of the association. The table to which the columns are added is chosen at random. The added columns have foreign key constraints that reference the primary key of the table that corresponds to the entity type on the other end of the association. Many-to-many (*:*) A join table is created, and for each key property in each entity type, a column is added to the table. The columns have foreign key constraints that reference the primary keys in the tables created based on the entity types on the ends of the association. The primary key of the created table will be a compound primary key that consists of all the columns in the table. The goal of the EDM in regards to relationships is to provide flexible modeling capabilities, allowing explicit reference and navigation based on a pure peer-to-peer relationship model. Navigation Properties We talked about properties a bit ago when we discussed scalar properties. Entities also have navigation properties. Navigation properties are simply pointers to related entities, shortcut properties used to locate the entities at the ends of an association. Navigation properties help describe navigable paths between associations. Figure 3-15 shows the EDM created earlier, highlighting the entities contained in the EDM. In the figure, the Employee navigation property in the Person entity is highlighted. The properties of that navigation property are shown on the right in the Properties pane. In this figure you can see that the navigation properties of each entity inherit the name of their related entity. 46
  11. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Figure 3-15. Navigation properties From the figure you can see that there is indeed a foreign key defined between the Person and Employee entities on the BusinessEntityID property. You can also see much of the same type of information that you see when looking at the association information in Figure 3-14, such as multiplicity for the corresponding end of the association as well as the role the navigation property belongs to. Due to the way associations and navigation properties are handled, navigation between entities is very easy. For example, Figure 3-15 shows the Person and Employee entities each with an associated navigation property to the corresponding related entity, providing a path that allows navigation between the two entities. As such, it is now possible to easily locate an instance of the Person entity from the Employee entity, or vice-versa. Navigation properties also provide collection functionality. Let’s use the case of the SalesPerson and SalesOrderHeader for this example. In my EDM, the object model will contain an Add method on the SalesOrderHeader property, which allows new SalesOrderHeader instances to be created and added. Mapping Details The Mapping Details window the lets you view and edit mappings between the conceptual model and the storage model within the EDM. Changes made here are applied immediately to the .edmx file. Through this window you can map entity types or associations. Figure 3-16 shows table column mapping. There are three columns: the Column column lists the table column name and data type, the Operator column provides the mapping type, and the Value/Property column is the entity column that the table column is directly mapped to. 47
  12. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Figure 3-16. Mapping details Lifting the EDM Hood Now that we know how the visual part of the EDM works, the next step is to look at the makeup of the EDM. Visually, only a small part of the model is viewable via the Designer, but most of the work is done under the hood and it will really help you to know what goes on underneath there. Double-clicking on the .edmx files always opens up the EDM in the Designer, so to look under the hood you’ll need to implement a “right-click” approach. So, right-click on the .edmx file and select Open With... from the context menu. This will open the Open With dialog box, shown in Figure 3-17. 48
  13. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Figure 3-17. Opening the EDM in XML We want to look at the EDM in its raw form, so select XML Editor (as shown in Figure 3-17) and click OK. If you have the EDM Designer open it will ask you to close it before continuing. Click Yes. What you are now looking at are 547 lines of raw XML. If you added more or fewer tables, views, or stored procedures your XML might be more or fewer rows, but in my example, there are 547 lines. However, the line count is not important—what is important is the content of the XML. It might look intimidating, but it really is not. The .edmx file is really a combination of three EDM metadata files: the conceptual schema definition language (CSDL), store schema definition language (SSDL), and mapping specification language (MSL) files. The best way to view these is to collapse the individual sections, as shown in Figure 3-18. This will break it down into about 14 lines. 49
  14. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Figure 3-18. EDM in raw XML From here, we’ll look at the individual sections. The EDM Model Parts As stated earlier, the EDM is really comprised of several different pieces within two different sections. In Figure 3-18 you can see the two different sections, the Runtime and the Designer sections. The Runtime section is made up of three additional sections, which were mentioned briefly earlier: SSDL: Storage Schema Definition Language, also known as the conceptual model • CSDL: Conceptual Schema Definition Language, also known as the storage model • CS (MSL): Mapping information • Each of these sections is discussed in the following pages. The SSDL Section As the name suggests, the SSDL (StorageModel) section is an XML schematic representation of the mapped data store. In this case, it is the tables selected from the AdventureWorks2008 database. Figure 3-19 shows the top of this section expanded. This section itself is about 240 lines long for the objects selected from the database in our example. 50
  15. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Figure 3-19. SSDL Obviously it wouldn’t be prudent to paste the entire XML section in here, but I have tried to include enough to give you an idea of what this section is all about. I’ll also include some code snippets as well to illustrate how the SSDL is implemented. First, there are a few things that need to be highlighted that will help distinguish this section from others. Take a look at the Schema element. The Namespace includes “.Store”—an apparent indication that this mapped to the data store and not to the conceptual model or anything else. There are other name/value pairs that provide visual clues as to the source of the storage. You’ll notice a Provider attribute and a ProviderManifestToken attribute. These two attributes show what provider was used to connect to the data store and the version of the data store. In this case, the System.Data.SqlClient provider was used to access a SQL Server version 2008 database. There is also an EntityContainer element, which in the SSDL describes the persisted data store. This is usually a database such as SQL Server. The name for this element is typically the name of the database with the words “StoreContainer” appended to the end. You’ll also notice in Figure 3-19 a element. This element defines a query that maps to data-store views through client-side projection inside the EDM. These mappings are read-only. Client-side projection is useful in that users would need to map all store-view columns manually. OK, with that let’s take a look at some of the content further on in the SSDL section. 51
  16. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT EntityType Element As you scroll down in the XML you’ll see one or more elements. There will be one for each table included in the EDM. The entity type names are the actual names of the tables in the database. The element is used in the SSDL to define metadata about entities in the storage model that is used by the EDM. For example, the following was taken from the SSDL from our example: One thing to keep in mind is that the Type attribute of the Property element is the provider data types, meaning the SQL Server data types. The element specifies which properties make up the identity key of the table. Association Element The Association element defines how the database defines the relationships between the given tables. In the following code sample taken from the SSDL, the Association element defines the primary key and foreign key relationships between the Employee table and the Person table. Much of the information is pulled directly from the database. For example, the Name attribute is the name of the foreign key found in the database. 52
  17. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT One of the most important elements in the association is the ReferentialConstraint element. This element serves two main purposes: Relationship direction: Using the Principle and Dependent elements, this specifies • the direction in a relationship. In the previous code, Employee is dependent on Person. Ensures data integrity: Specifies data integrity between entities. For example, a • row in the Employee table cannot exist in the Person table. This rule exists in the database via the foreign key, but this is also enforced in the Entity Framework because of the ReferentialConstraint element. As data is sent to the database, the Entity Framework APIs will use the ReferentialConstraint element to check any and all data against this rule before it is sent to the database. Anything that does not pass the ReferentialConstraint rule will result in the data not even being sent to the database. Related to the element is the element. Directly below the element you will find one or more elements. This element specifies the associations in the SSDL metadata. For example, the following XML defines the association shown previously. An AssociationSet is simply a container for an association. This might be confusing because you also have an EntityContainer for entities, which is ideal because it is very possible and expected to have many Employee entities, for example. But does that mean you can have a collection of associations? The answer is that associations between entities are also objects, and therefore you can have multiple association objects. An example of this would be where you have a single SalesPerson with multiple orders (SalesOrderHeader), and as such you would have an association (FK object) for each relationship. OK, now on to the CSDL. The CSDL Section The CSDL (Conceptual Schema Definition Language), as the name suggests, is simply a conceptual schema. In other words, it is a conceptual design template for the object model that applications will use to build their applications against. Figure 3-13 shows the top of this section expanded. This section itself is about 170 lines long. If you think that this looks similar to the SSDL, you are correct. However, there are some differences in the elements and differences in the purposes of the elements. This section also has a Schema element as well as EntityType elements and Association elements. The CSDL also has an EntityContainer element, but for the CSDL this element controls the scope of entity and associations in the defined object model. As you can see in the next figure, the EntityType and AssociationSet definitions are all contained within the EntityContainer. The EntityContainer exposes the EntitySets, making it the entry point for executing queries against the model. When you write queries, you write them against the EntitySet, and it is the responsibility of the EntitySet to pass permission on to the entity itself. For the CSDL, the name of this element is typically the name of the database with the word “Entities” appended to the end. You can see this in Figure 3-20. 53
  18. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT Figure 3-20. CSDL Let’s take a look at a few things we also looked at in the SSDL section, starting with the Schema element. The Namespace is missing the “.Store” appendage. The name/value pairs found in the SSDL that were used to map and connect to a data store and specify data store version are also gone. This makes sense because we are dealing conceptually and not with physical storage. OK, with that let’s take a look at some of the content further on in the CSDL section. EntityType Element In the CSDL, the EntityType element is used to specify an object in the domain of the designed application. Another way to say that is an EntityType is a data type in the conceptual model. The following code shows the EntityType for the Employee entity taken from our example. 54
  19. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT This code looks much like the EntityType of the SSDL, but you’ll notice some additional information: Types: Unlike the SSDL, the data types that define these properties are primitive • types, or simple types, of the Entity Framework object model that align with the .NET Framework data types. String data types: String data types have additional attributes such as Unicode and • FixedLength. Also, you’ll notice the addition of a NavigationProperty element. This element defines a shortcut that is used to navigate between entities that are related using the Association type. The Key element is used differently in the CSDL than in the SSDL. The Key element defines which property or properties make up the identity key for the entity. It also provides tracking at the entity level, meaning that you can track changes to the entity and track updates and entity refreshes. Associations Lastly, let’s look at the association for the CSDL. It looks nearly identical to an association defined in the SSDL, but the one difference in this example is that where the Type attribute included “.Store” while the Type attributes for the CSDL do not. 55
  20. CHAPTER 3 ■ THE ENTITY DATA MODEL INSIDE AND OUT You should be able to look at these associations and see that they include all of the same information that you see in Figure 3-7. Two ends are defined, one with a role of Person and one with a role of Employee. The association Name comes from the predefined relationship established in the database. The multiplicity is also defined, and you can see that for every Person there will be at least one Employee, but only a single Employee can be associated to a single Person. OK, now on to the CSDL. The CS (MSL) Section The mapping section is a specification that is used to connect the CSDL types to the database metadata defined in the SSDL. Figure 3-21 shows the mapping from our example. Figure 3-21. MSL The mapping is a layer that resides between the conceptual and store layers. Its entire purpose is to provide the mapping between entities (entity properties) to the tables and columns in the data store. Notice in the previous figure that the section is actually called C-S Mapping, referring to conceptual storage mapping. Can these mappings be modified? Absolutely. The mapping layer provides model customization if you like to work with XML. However, there is a better way to work with the mapping and that is 56
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2