The inheritance mapping relationships in EF TPH, TPT and TPC explanations, and a few concrete examples

Source: Internet
Author: User

The inheritance mapping relationships in EF TPH, TPT and TPC explanations, and a few concrete examples

This section explains the inheritance mapping relationship in EF, which is divided into TPH, TPT, TPC. Specific:

1.tph:table Per Hierarchy

This is the default inheritance mapping relationship for EF: A table holds all the columns of the base class and subclass, and the automatically generated discriminator column is used to differentiate the data of the base class and subclass. Create a new resort resort entity class try:

    <summary>  ///Resort class///</summary> public class resort:lodging//here inherit the lodging class    { Public        string Entertainment {get; set;}  Entertainment public        string Activities {get; set;}  Activity    }

Previous accommodation class lodging has a property isresort indicates whether the resort, now can be commented out, there is a new class resort to inherit lodging to indicate whether it is a holiday resort, run the program will eventually generate a table:

Instead of generating a resorts table, the attributes in the Resrot entity class are generated into the lodgings tables. A list of discriminator, which is the default, is used to indicate which class the data came from, and to continue adding a method for inserting lodging table data:

        private static void Insertlodging ()        {            var lodging = new CodeFirst.Model.Lodging            {                Name = "Rainy Day Motel ",                Destination = new CodeFirst.Model.Destination                {                    Name =" Seattle, Washington ",                    country =" USA "                }            };            using (var context = new CodeFirst.DataAccess.BreakAwayContext ())            {                context. Lodgings.add (lodging);                Context. SaveChanges ();            }        }

Add a method to insert resort table data:

        private static void Insertresort ()        {            var resort = new CodeFirst.Model.Resort            {                Name = "Top Notch Resort an D Spa ",                Milesfromnearestairport = +,                activities =" spa, hiking, skiing, ballooning ",                Destination = new Codef Irst. Model.destination                {                    Name = "Stowe, Vermont",                    country = "USA"                }            };            using (var context = new CodeFirst.DataAccess.BreakAwayContext ())            {                context. Lodgings.add (resort);                Context. SaveChanges ();            }        }

The following data can be obtained by invoking the two insertion method in the Main method:

Two inserted data into a table. The discriminator column represents which column the data comes from. Of course it can be configured, it must be configured with the Fluent API, Data annotation is powerless to configure in the Lodgingmap:

This. map<codefirst.model.lodging> (L = = {L.requires ("from"). HasValue ("standard"); }); map<codefirst.model.resort> (L = = {L.requires ("from"). HasValue ("Resort"); });

Generated our specified from column, data standard, resort respectively from the lodging and Resrot table, the image point is the 1th hotel is a normal hotel, 2nd is a holiday resort hotel:

Of course, here you can even set the parameters in the HasValue method to True and false, with a Boolean type of data to differentiate between the hotel and the holiday resort more image, park friend Lk8167 gave a more image of the general salesperson and Sales Manager example

2.tpt:table Per Type

The parent class and subclass are in different tables. To configure TPT using data annotation:

Press CTRL + C to copy the code

Press CTRL + C to copy the code

Or use the Fluent API configuration:

Press CTRL + C to copy the code

Press CTRL + C to copy the code

Note: The FLUETN API that configures TPH above needs to be commented out in the Run program, which is the configuration of the test TPH. At the same time, release the remark: context. Database.initialize (TRUE); The entity is not modified here, but the database needs to be rebuilt. The final database is this:

Both the parent and subclass entities have a table, and the child table finds the parent table through the primary key Lodgingid:

3.tpc:table Per Concrete Type

Create a table for each subclass that corresponds to the column that contains the properties of the base class in the table that corresponds to the child class, and the columns that correspond to the subclass-specific properties. The fluent API that was previously configured for TPT needs to be commented out first, and then we will not be able to configure it with the data annotation via the Fluent API Tpc,tpc:

Press CTRL + C to copy the code

Press CTRL + C to copy the code

The resulting database:

As can be seen, the subclass resorts class also has all the properties of the base class.

Note: In order to facilitate the test to generate TPC, I annotated all the lodging table navigation properties, mainly with destination's one-to-many relationship, destination class also need to comment out the lodging attribute and the Fluent API relationship configuration, Otherwise, the program will report dataexception error.
An exception occurred while initializing the database. See the InnerException for details.

When you download the demo, you need to comment out the navigation properties of the lodging class first. Of course not comment to want to keep also can, must set foreign key to nullable type, refer to programming Entity Framework:code first fifth chapter avoiding Mapping Exceptions with TPC

How do you configure inheritance mappings in these ways, and which one should be used in the actual project?

    1. It is not recommended to use TPC (type Per concrete type) because the instance or instance collection of other classes contained in a neutron class in TPC mode cannot be mapped to a relationship between tables. You have to let code first perceive the relationship between them by manually adding the primary key properties of the dependent class to the class, which is the opposite of the original intention of using code first;
    2. From the query performance, the TPH will be better, because all the data exists in a table, do not need to use join in the data query;
    3. In terms of storage space, TPT will be better because all the columns in the TPH are in one table, and the records in the table cannot use all the columns, so many columns have null values and a lot of storage space is wasted;
    4. In terms of data validation, TPT is better because the columns for many of the subclass properties in TPH are nullable, adding complexity to data validation.

Excerpt from here, the source code of this article

The end of this series, mainly on how EF uses code first to configure the database, basically handwritten configuration, you may have thought that there will be tools to automatically configure these relationships, by the way, is EF Power tools. This tool is quite intelligent and can be configured directly for all relationships. However, individuals are advised not to have much of a relationship with their own handwriting fluent API to configure.

In addition, the previous configuration of a long time for a pair of many, many-to-many relationships. How do you use EF to search and change these data? There will also be a series of articles explaining how EF operates the database, so stay tuned.

EF Code first series article Navigation:
  1. EF Code First Experience
  2. The default mappings in EF and how to use data annotations and the fluent API to configure the database mapping this section source code
  3. The usage of the self-growth, timestamp, and complex types of GUID type data in EF this section source code
  4. A pair of one or one-to-many, many-to-many relationships in EF configuration and cascade Delete this section source code
  5. The inheritance mapping relationships in EF TPH, TPT and TPC explanations and some specific examples of the source code in this section

The inheritance mapping relationships in EF TPH, TPT and TPC explanations, and a few concrete examples

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.