Entity Framework 6 Recipes Chinese translation series (36), entityframework

Source: Internet
Author: User

Entity Framework 6 Recipes Chinese translation series (36), entityframework
For the original intention of translation and why I chose Entity Framework 6 Recipes, see section 6-12 TPC inheritance ing modeling at the beginning of this series.

Problem

  You have two or more tables with data similar architectures. You want to use TPC inheritance ing to model these tables.

Solution

Suppose we have a table from 6 to 18.

Figure 6-18 table Toyota has a similar structure with BMW, which can be a derived type derived from an object Car.

 

In Figure 6-18, Toyota and BMW have similar Schemas and describe similar data. The BMW table only has an additional column. It uses a bit value to indicate whether the corresponding instance has the collision-avoidance feature. In modeling, we want to use a base class to hold the public attributes of Toyta and BMW tables. In addition, we also want to express the one-to-many relationship between dealers and vehicle inventory. Figure 6-22 shows the final model.

Follow these steps to create a model:

1. Add an ADO. NET Entity Data Model (ADO. NET Entity Data Model) to your project and import tables Toyota, BMW, CarDealer, and Dealer;

2. Right-click the designer and select Add (new) Entity (Entity ). Name the new object as a Car. Do not check the Create Key property check box;

3. Right-click the physical Car and select Properties ). Set the Abstract attribute to True;

4. You can use Cut/Paste (Cut/Paste) to move the public attributes of the object Toyota and BMW to the physical Car. Make sure that the Toyota entity has no attributes. The BMW entity only has the CollisionAvoidance entity. These two entities will inherit the public attributes from the entity Car;

5. Right-click the Car object and select Add (Add) inherit Inheritance (inherit ). Select Car as the base class and BMW as the derived class.

6. Repeat the previous operation and select Car as the base class and Toyota as the derived type.

7. Right-click the CarDealer object and select Delete ). When you are prompted whether to delete CarDealer from the storage model, select No );

8. Right-click the designer and select Add Association ). The name is associated with CarDealer. Select Dealer on the left, set the multiple to 1, select the Car on the right, and set the multiple. Name the Car navigation attribute Dealer and the Car navigation attribute. Make sure that you do not select Add foreign key properties (Add foreign key properties );

9. Select Association and view the Mapping Details window ). Under Add a Talbe or View, select CarDealer. Ensure that the DealerId attribute is mapped to the DealerId column and the CarID attribute is mapped to the CarId column;

Right-click the solution browser. in the edmx file, select Open With XML Editor, and edit the ing section using the changes in code listing 6-3 to the entity BMW and Toyota.

Code List 6-35.Ing entities BMW and Toyota to tables

 1     <EntitySetMapping Name="Cars"> 2                 <EntityTypeMapping TypeName="IsTypeOf(Apress.EF6Recipes.BeyondModelingBasics.Recipe12.BMW)"> 3                     <MappingFragment StoreEntitySet="BMW"> 4                         <ScalarProperty Name="CollisionAvoidance" 5                                         ColumnName="CollisionAvoidance" /> 6                         <ScalarProperty Name="CarId" ColumnName="CarId"/> 7                         <ScalarProperty Name="Model" ColumnName="Model"/> 8                         <ScalarProperty Name="Year" ColumnName="Year"/> 9                         <ScalarProperty Name="Color" ColumnName="Color"/>10                     </MappingFragment>11                 </EntityTypeMapping>12                 <EntityTypeMapping TypeName="IsTypeOf(Apress.EF6Recipes.BeyondModelingBasics.Recipe12.Toyota)">13                     <MappingFragment StoreEntitySet="Toyota">14                         <ScalarProperty Name="CarId" ColumnName="CarId"/>15                         <ScalarProperty Name="Model" ColumnName="Model"/>16                         <ScalarProperty Name="Year" ColumnName="Year"/>17                         <ScalarProperty Name="Color" ColumnName="Color"/>18                     </MappingFragment>19                 </EntityTypeMapping>20             </EntitySetMapping>

The final model 6-19 is shown.

Figure 6-19 concept model describes the derived types of BMW and Toyota represented as separate tables in the database

 

Principle

TPC is an interesting inheritance model that allows each derived object to be mapped to a separate physical table. From a practical perspective, tables have at least some common architectures. This public architecture is mapped to the base class, and the additional part of the architecture is mapped to the derived class entity.To make the TPC inheritance model work normally, the object key must be unique in the entire related table (such as the tables Toyota and BMW in this example )..

The base object is marked as an abstract type and is not mapped to any table.In TPC, only derived type entities are mapped to tables..

In our example, we mark the Car object as an abstract type and do not map it. Note: In the ing of code listing 6-35, we only map the derived types BMW and Toyota. We move the common attributes (CarID, Model, Year, and Color) to the base class object. A derived class only contains its own unique attributes. The BMW entity instance has an additional attribute CollisionAvoidance.

Because the entity Toyota and BMW derive from the entity Car, they become part of the same entity set Cars.This means that the object key must be unique in the object set that contains the entire derived type.. Because entities are mapped to different tables, I may encounter the same key. To avoid this, we set the CarId column of each table as the ID column. For the BMW table, we initialize the seed (base) of the primary key to 1 and set the increment to 2, which will create an odd value for the primary key CarId. For the Toyota table, we initialize the seed of the primary key to 2 and set the increment to 2. This will create an even value for the primary key CarId.

When using TPC to inherit ing modeling relationships, defining relationships in derivation is better than defining relationships in a base class. This is because the Entity Framework does not know which physical table is associated with the other end at runtime. Of course, in our example, we provide a separate table (CarDealer) that contains the relationship. This allows us to map data to CarDealer tables in the base class.

In many practical applications that use TPC to inherit ing, the most common thing is to process archived data. Suppose your e-commerce website has many years of order data. At the end of each year, you Archive your orders for the previous 12 months in the Archive table and prepare an empty table for the New Year. You can use the method demonstrated here to model the current and archived orders using TPC.

  Compared with other inheritance mappings, TPC inheritance ing has a particularly important performance advantage. When querying a group of data types, queries are generated for the underlying database tables, without any additional join connections like The TPT inheritance ing or filtering like the TPH. This performance advantage is crucial for large datasets or models with several derived types.

  The disadvantage of TPC inheritance ing is that it includes overhead for potential duplicate data and ensures the unique complexity of the primary key throughout the relevant table.. In the archiving scenario, data is not duplicated, but simply distributed in multiple tables. In other scenarios, data (attributes) may be duplicated in the relevant table.

Code List 6-36 demonstrates how to insert and retrieve data from a model.

Code List 6-36. insert and retrieve data from the Model

 1  using (var context = new Recipe12Context()) 2             { 3                 var d1 = new Dealer { Name = "All Cities Toyota" }; 4                 var d2 = new Dealer { Name = "Southtown Toyota" }; 5                 var d3 = new Dealer { Name = "Luxury Auto World" }; 6                 var c1 = new Toyota 7                 { 8                     Model = "Camry", 9                     Color = "Green",10                     Year = 2014,11                     Dealer = d112                 };13                 var c2 = new BMW14                 {15                     Model = "310i",16                     Color = "Blue",17                     CollisionAvoidance = true,18                     Year = 2014,19                     Dealer = d320                 };21                 var c3 = new Toyota22                 {23                     Model = "Tundra",24                     Color = "Blue",25                     Year = 2014,26                     Dealer = d227                 };28                 context.Dealers.Add(d1);29                 context.Dealers.Add(d2);30                 context.Dealers.Add(d3);31                 context.SaveChanges();32             }33 34             using (var context = new Recipe12Context())35             {36                 Console.WriteLine("Dealers and Their Cars");37                 Console.WriteLine("======================");38                 foreach (var dealer in context.Dealers)39                 {40                     Console.WriteLine("\nDealer: {0}", dealer.Name);41                     foreach (var car in dealer.Cars)42                     {43                         string make = string.Empty;44                         if (car is Toyota)45                             make = "Toyota";46                         else if (car is BMW)47                             make = "BMW";48                         Console.WriteLine("\t{0} {1} {2} {3}", car.Year,49                                            car.Color, make, car.Model);50                     }51                 }52             }

The output of code list 6-36 is as follows:

Dealer: Luxury Auto World    2014 Blue BMW 310iDealer: Southtown Toyota    2014 Blue Toyota TundraDealer: All Cities Toyota    2014 Green Toyota Camry

 

 

 

Entity Framework exchange QQ group: 458326058. You are welcome to join us.

Thank you for your continued attention, my blog address: http://www.cnblogs.com/VolcanoCloud/

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.