Entity Framework 6 Recipes Chinese translation series (37), entityframework
For the original intention of translation and why I chose Entity Framework 6 Recipes, see section 6-13 of this series to apply conditions in the base class.
Problem
You want to derive a new entity from an existing model, allowing the base class to be instantiated.
Solution
Suppose you have a model 6-20.
Figure 6-20 models that contain Invoice entities
This model only contains a separate entity Invoice (Invoice ). We want to derive a new entity from Invoice, which indicates the deleted Invoice. This will allow us to perform different operations on valid shipment orders and deleted shipments with clearer business logic. Follow these steps to add the derived type:
1. In the Mapping Details window (ing Details window), view the Invoice information of the entity and add a condition to the IsDeleted column. When IsDeleted = 0 (When the IsDeleted column value is 0 ), see Figure 6-21.
Figure 6-21 invoing Invoice object when the IsDeleted column is 0
2. Now the IsDeleted column is used as a condition. We need to remove it from the scalar attribute of the object. Right-click the IsDeleted attribute of the entity Invoice and select Delete );
3. Right-click the designer and select Add (new) Entity (Entity ). Name the new object DeletedInvoice and select Invoice as the base class;
4. In the Mapping Details window (ing Details window), view ing information of DeletedInvoice. Map it to the Invoice table and add a condition to the IsDeleted column, as shown in Figure 6-22. When IsDeleted = 1 (When the value of the IsDeleted column is 1.
Figure 6-22 edinvoice object when the IsDeleted column is 1
Contains the final model of the Invoice entity and the derived DeletedInvoice entity, as shown in 6-23.
Figure 6-23 conceptual models of entity Invoice and DeletedInvoice
Principle
There are two different ways to model our Invoice and DeletedInvoice. The method we demonstrated is only recommended in the following cases. You have an existing model and code library. You want to add DeletedInvoice, a derived entity, and minimize the impact on existing code. For a new model, it is better to derive an ActiveInvoice type and a DeleteInvoice type from the base class Invoice. If you select this method, you need to mark the base class as an abstract type.
Here we use the method we demonstrated. As shown in code list 6-37, you can decide whether to use the casting or OfType <> () method to convert DeletedInvoice. However, you cannot select the entity Invoice separately, which is the biggest disadvantage of this method.
Code List 6-37.Use the as operator to determine whether we have an Invoice type or a DeletedInvoice type.
1 using (var context = new Recipe13Context()) 2 { 3 context.Invoices.Add(new Invoice 4 { 5 Amount = 19.95M, 6 Description = "Oil Change", 7 Date = DateTime.Parse("4/11/13") 8 }); 9 context.Invoices.Add(new Invoice10 {11 Amount = 129.95M,12 Description = "Wheel Alignment",13 Date = DateTime.Parse("4/01/13")14 });15 context.Invoices.Add(new DeletedInvoice16 {17 Amount = 39.95M,18 Description = "Engine Diagnosis",19 Date = DateTime.Parse("4/01/13")20 });21 context.SaveChanges();22 }23 24 using (var context = new Recipe13Context())25 {26 foreach (var invoice in context.Invoices)27 {28 var isDeleted = invoice as DeletedInvoice;29 Console.WriteLine("{0} Invoice",30 isDeleted == null ? "Active" : "Deleted");31 Console.WriteLine("Description: {0}", invoice.Description);32 Console.WriteLine("Amount: {0:C}", invoice.Amount);33 Console.WriteLine("Date: {0}", invoice.Date.ToShortDateString());34 Console.WriteLine();35 }36 }
The output of code listing 6-37 is as follows:
Active InvoiceDescription: Oil ChangeAmount: $19.95Date: 4/11/2013Active InvoiceDescription: Wheel AlignmentAmount: $129.95Date: 4/1/2013Deleted InvoiceDescription: Engine DiagnosisAmount: $39.95Date: 4/1/2013
6-14 create independent association and foreign key Association
Problem
You want to use Model First to create an independent association and a foreign key Association.
Solution
Independent Association and foreign key Association help us maintain the integrity of the reference in the database architecture, and provide a navigation path pointing to the associated entity. To use Model First to create Foreign keys and independent associations, follow these steps:
1. Add a new ADO. NET Entity Data Model (ADO. NET Entity Data Model) to your project, select an empty Model when prompted to select the Model content, and click Finish. This creates an empty design interface;
2. Right-click the designer and select Add (new) Entity (Entity ). Name the new object as User and click OK );
3. Right-click the newly added object and add a scalar property UserName for it;
4. Right-click the designer and select Add (new) Entity (Entity ). Name the new object PassordHistory and click OK );
5. Right-click the newly added object and add a scalar attribute LastLogin to it. Right-click LastLogin and change its type to DateTime;
6. Right-click the Object User and select Add (Add) Associate Association ). To create a foreign key Association, check the Add froreign key properties to the PasswordHistory Entity check box. to create an independent association, do not select the check box.
7. Right-click the designer and select Generate Model from Database (Generate Model from Database ). Select a database connection and complete the wizard. This will generate the storage layer and ing layer of the model, and generate a script to generate a database from the model.
If you choose to create a foreign key Association, see model 6-24. If you choose to create an independent association, see model 6-25.
Figure 6-24. Foreign key association between User and PasswordHistory
Figure 6-25. Independent Association between User and PasswordHistory
Principle
For a foreign key Association, the foreign key is treated as an attribute of the dependent object. Exposing Foreign keys allows you to use code that is the same as managing other property values to manage many associated aspects. The most important help is in offline scenarios. We will see relevant content in Chapter 9. Foreign key Association is the default behavior of the object model.
For independent associations, foreign keys are not used as attributes of dependent entities. This makes the concept layer of the model somewhat refreshing, because the associated implementation details are not introduced here. In earlier versions of the Entity Framework, only independent association is supported.
6-15 modify an independent association as a foreign key Association
Problem
If you use an independent association model, you want to change the independent association into a foreign key Association.
Solution
Suppose you have a model 6-26.
Figure 6-26. Use an independent association model between vehicles and tickets
Follow these steps to modify an independent association as a foreign key Association:
1. Right-click the Ticket object and select Add (new) Scalar Property (Scalar attribute ). And rename it to LicenseNumber );
2. In the detaing Details window (ing Details window), view the associated ing information and select <Delete> from the ing to the Ticket control to remove the ing of the Ticket table;
3. Right-click Association, view properties, and click reference constraint control. In the displayed dialog box, select Vehicle from the Principal drop-down menu. Set Principal Key and Dependent Property to LicenseNumber, as shown in Figure 6-27.
Figure 6-27. Create reference constraints for foreign key associations
4. In the Mapping Details window (ing Details window), view the ing information of the entity Ticket, and map the LicenseNumber column to the LicenseNumber attribute, as shown in Figure 6-28.
Figure 6-28. ing the LicenseNumber attribute to the LicenseNumber column for the entity ticket
The final model is shown in Figure 6-29.
Figure 6-29. Change independent join to foreign key join Model
Principle
After you change an independent association to a foreign key Association, most of your existing code can run normally. Now, it is very easy to associate two entities. You only need to set an appropriate value for the foreign key attribute. To change a link in an independent association, you need to create a new instance for the object key and set the xxxReference. EntityKey of the object to the new instance. In foreign key Association, you only need to set the value of the foreign key attribute as the primary key value.
Foreign key associations currently do not support many-to-many associations because these associations must be mapped to the underlying chain tables. Maybe, in future object framework versions, foreign key associations support multi-to-many associations by attaching loads.
At this point, Chapter 6 is over. Next we will enter Chapter 7. This article is a bit long. Thank you for reading it!
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/