Entity Framework Code First Relational Mapping Convention "L Forwarding"

Source: Internet
Author: User

This essay list:

1. Foreign key Column name default convention

2, one-to-many relationship

3. One-to-one relationship

4. Many-to-many relationships

5. A one-to-many reflexive relationship

6. Many-to-many reflexive relationships

In a relational database, it is not always the case that all the tables exist separately, but they are related to each other. There can be a foreign key dependency between two different tables, and a table can have a reflexive relationship (a field in the table refers to a primary key, which is also a foreign key field).

Some convention rules for the Entity Framework Code first default multi-relationship:

  One -to-many relationships: Two classes contain a reference and a collection property, or a class that contains a reference property of another class, or a class that contains a collection property of another class. As in the next example category and Product class, the Entity Framework Code first can be represented in 3 ways, in order to have a one-to-many relationship between category and product:

  1>, define the Icollection<product> Products collection property in the Category class, and define the category category reference property in the Product class.

  2>, icollection<product> products collection properties are defined only in the category class.

  3>, the category category reference attribute is defined only in the Product class.

  Many-to-many relationships: Two classes each contain a collection property for each other. As in this next example of the user class and role class, to make a many-to-many relationship between user and role, that is, one can belong to multiple roles, a role can have multiple users, you need to define a icollection<role in the user class > Roles Collection Properties, and you need to define a icollection<user> users property in the role class.

  Two-to- one relationship: Two classes each contain a reference property for each other. As in this next example of the user class and the UserProfile class, in order to have a one-to-userprofile relationship between user and a, you need to define a userprofile userprofile reference property in the user class. Also define a reference property for the user user in the UserProfile class.

The following describes the default conventions for generating foreign keys for the Entity Framework Code first, and shows the Entity Framework code first handles the relationship between a table and multiple tables through an instance.

  1. Foreign key Column name default convention

The Entity Framework Code First has 3 ways of naming foreign key columns when creating foreign keys based on default conventions. In the programming Entity Framework Code first book, the 3 types of foreign key column names are agreed by:[target type key name], [target type name] + [target TYP E Key name], or [Navigation property name] + [target type key name], the corresponding Chinese translation is: [The key name of the target kind],[the target type name]+[the target type key name], or the [reference attribute name]+ [Target type key name].

The foreign key generated by the Entity Framework Code first foreign key default constraint satisfies 3 different conditions, and the foreign key column name has 3 different naming conventions. and tested, there is a priority between the 3 different foreign key name names: [Key name for target type] > [Reference property name]+[target type key name] > [Target type name]+[target type key name]. Next, take the product class and category class as an example, test the foreign key column name in 3 different generation method, category and product is a one-to-many relationship.

  1>, [key name of the target type]

This approach requires that the key column names in the product table are the same as the primary key column names in the category table, so there is a requirement to have the attribute defined in the product class as the primary key in the category class. If the primary key attribute in the category class is CategoryID, you need to define a CategoryID attribute in the product class as well.

File Category.cs:

View Code

File Product.cs:

View Code

Description: A virtual modification of the reference and collection properties in the category and product classes is used for the lazy load function of the entity Framework Code first. Without virtual decoration, lazy loading will not be enabled when an instance of the category class queries the containing product instance. Of course, the entity Framework Code first delay loading is not necessary, so the virtual modifier can also be added.

After defining the above two classes, no more mapping configuration of the entity Framework Code first to the database is added, and after running, the resulting data table structure is:

As can be seen from the generated categories and the Products table structure, the foreign key CategoryID in the Products table is the same as the primary key name categories the referenced table. The Execute script that tracks the entity Framework Code first build data table can see the SQL statement that generated the foreign key.

ALTER TABLE [dbo]. [Products] ADD CONSTRAINT [Fk_dbo. Products_dbo. Categories_categoryid] FOREIGN KEY ([CategoryID]) REFERENCES [dbo]. [Categories] ([CategoryID]) On DELETE CASCADE

At the same time, from the script that generates the foreign key, it can be seen that the Entity Framework Code first generates a foreign key with the Cascade Delete feature enabled. That is, when a record in the Categories table is deleted, the database is automatically associated with deleting records belonging to that category in the Products table.

The Products table generated in the database to see the foreign key fk_dbo. Products_dbo. The Categories_categoryid property, which does have the Cascade Delete feature enabled.

  2>, [target type name]+[target type key name]

This approach requires that the key column name in the product table is the category class name in the +category class, that is, the foreign key name generated in the Products table is Category_categoryid. Example: Adding a collection property of icollection<product> products to the category class, without any code associated with the category in the Product class, and no CategoryID attribute defined.

File Category.cs:

View Code

File Product.cs:

View Code

After defining the above two classes, no more mapping configuration of the entity Framework Code first to the database is added, and after running, the resulting data table structure is:

3>, [reference property name]+[target type key name]

This approach is required in the product table for the foreign key column name to refer to the category in the product class for the property name + primary Key name of the category class. For example, if you define a category property cat in the product class, the generated foreign key name is Cat_categoryid.

File Category.cs:

View Code

File Product.cs:

View Code

After defining the above two classes, no more mapping configuration of the entity Framework Code first to the database is added, and after running, the resulting data table structure is:

There is a priority between naming 3 different foreign key names: [Key name for target type] > [Reference property name]+[target type key name] > [Target type name]+[target type key Name] test method:

The highest priority of the key name of the target type: As long as the CategoryID attribute is defined in the product class, the foreign key column names generated in the Products table will only be CategoryID.

[Reference property name]+[target type key name] > [Target type name]+[target type key name]: Whenever a cat attribute is defined in the product class, the generated Products table foreign keys are only cat _categoryid.

  2, one-to-many relationship

The Entity Framework Code first generates a default convention for the foreign key relationship between data tables and the resulting foreign key column names when generating a data table from a defined class. However, such a contract can also be modified, such as a foreign key that does not satisfy the default foreign key contract as a generated table. Example: Category class and Product class, define an attribute in the product class CATID, to use the CATID property as a foreign key to the category of product reference, and follow the entity Framework Code The default convention for first is not. To do the required CATID as a foreign key, you can also use the data annotations and fluent API two ways to implement.

  1>, Data annotations mode

File class Category.cs:

View Code

File class Product.cs:

View Code

After defining the above two classes, no more mapping configuration of the entity Framework Code first to the database is added, and after running, the resulting data table structure is:

View the foreign key of the Products table CATID reference relationship:

Where, in the product class, the code for setting the CATID property to a foreign key is:

public int CatID {get; set;} [ForeignKey ("CatID")]public Virtual category category {get; set;}

The implementation of this paragraph can also be changed to:

[ForeignKey ("Category")]public int CatID {get; set;} Public virtual category category {get; set;}

  2>, Fluent API Way

File class Category.cs:

View Code

File class Product.cs:

View Code

File class PortalContext.cs:

View Code

Note: In the Onmodelcreating method of PortalContext.cs, the relationship configuration of the Fluent API form is added to the two entity classes category and product. For entity Framework Code First, the relationship between the two entity classes can be either added to the relationship mapping configuration in two classes, or you can add a relational mapping configuration to any of these entity classes. That is, in the PortalContext.cs onmodelcreating method, you can include only the category or relational mapping configuration that contains only the product class. From the experience and technique of using entity Framework Code First, we recommend that you configure the relationship mappings between the entities classes in classes that contain foreign keys. That is, onmodelcreating only adds a relational mapping configuration to the Product entity class, which has the advantage of having the foreign key configured in the entity class that references it when the category has more than one table referencing it, thereby reducing the complexity of the category class. It also benefits the maintenance of the code.

That is, the Onmodelcreating method in PortalContext.cs only requires the following definition:

protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) {    modelbuilder.entity<product> ()        . hasrequired (t = t.category)        . Withmany (t = t.products)        . Hasforeignkey (d = d.catid);}

The foreign key reference constraints generated by the Entity Framework Code first based on a one-to-many relationship are cascade-deleted by default, and you can disable cascading deletions between category and product in the following ways.

protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) {    modelbuilder.entity<product> ()        . hasrequired (t = t.category)        . Withmany (t = t.products)        . Hasforeignkey (d = d.catid)        . Willcascadeondelete (false);}

You can also disable a pair of cascade deletions in all the tables generated by the entity Framework Code first.

protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) {    modelbuilder.conventions.remove< Onetomanycascadedeleteconvention> ();}

Although the entity Framework Code first can support the foreign key column name customization, in the actual project, more foreign key column names are the same as the primary key column names of the referenced tables. That is, the primary key in the category table is CategoryID, and the name of the foreign key column in the product table is CategoryID.

The fluent API of the entity Framework Code first configures the mapping of entities classes to tables, and all of the entity classes and table mappings can be written in a single class, which facilitates code maintenance.

File class Category.cs:

View Code

File Class CategoryMap.cs, which describes the mapping between the category class and the resulting table:

View Code

File class Product.cs:

View Code

File Class ProductMap.cs, which describes the mapping between the product class and the resulting table:

View Code

PortalContext.cs Method of Onmodelcreating:

View Code

  3. One-to-one relationship

In one-to-one relationships, two tables have their own primary key, but you want to see which table's primary key also references the primary key of the other table as a foreign key. The example takes the user class and the UserProfile class as two classes with a one-to-many relationship, where the user class contains the UserID property as the primary key, and the UserProfile class contains the properties of the profileID as the primary key.

  1>, Data annotations mode

File class User.cs:

View Code

File class UserProfile.cs:

View Code

After defining the above two classes, no more mapping configuration of the entity Framework Code first to the database is added, and after running, the resulting data table structure is:

In the resulting data table, the primary key profileID in the UserProfile table is also referenced as a foreign key in the user table's primary key UserID.

To modify a file class User.cs:

View Code

To modify a file class UserProfile.cs:

View Code

The data table generated after the entity class executes the user primary key UserID will also reference the primary key profileID of the UserProfile table as a foreign key.

  2>, Fluent API Way

The Fluent API sets the table references generated by the entity class and is referenced through Withrequiredprincipal, withrequireddependent, and Withoptionalprincipal, Withoptionaldependent to set, an entity class using the Principal property will be referenced by a table generated by another entity class, and an entity class using the Dependent property will reference another entity class.

File class User.cs:

View Code

Map File class UserMap.cs:

View Code

File class UserProfile.cs:

View Code

Map File class UserProfileMap.cs:

View Code

After the above entity classes and entity mapping classes are executed, the resulting data table structure is as follows:

In the resulting table structure, the primary key userid in the UserProfile table also refers to the primary key userid of the user table as a foreign key. If you modify UserProfileMap.cs as follows, the resulting table structure of the user table's primary key UserID will be used as your foreign key to reference the UserProfile table's primary key UserID.

View Code

  4. Many-to-many relationships

Entity Framework Code first generates an intermediate table in addition to the attribute table defined by the entity class, when the data table is generated from the class of the defined many-to-many relationship. Used to represent a many-to-many relationship between two entity tables. Example entity class user and role are many-to-many relationships, one user can belong to multiple roles, and one role can contain multiple users.

File class User.cs:

View Code

File class Role.cs:

View Code

After defining the above two classes, no more mapping configuration of the entity Framework Code first to the database is added, and after running, the resulting data table structure is:

From the table structure above, it can be seen that, in addition to generating the users and Roles tables, the Roleusers table is generated as a mediation table, reflecting the many-to-many association relationships between the users table and the roles table after the entity class runs. The field generation rules for the mediation table roleusers are in accordance with the [target type name]+[target type key name] convention.

When the Entity Framework Code first generates a many-to-many association table based on the default convention, many-to-many data cascade deletions are enabled by default, and you can add code to disable it.

protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) {    //disables cascade deletion    of many-to-many relationships tables Modelbuilder.conventions.remove<manytomanycascadedeleteconvention> ();}

Fluentapi Implementation Method:

File class User.cs:

View Code

Map File class UserMap.cs:

View Code

File class Role.cs:

View Code

Map File class RoleMap.cs:

View Code

The resulting table structure after running:

  5. A one-to-many reflexive relationship

A one-to-many reflexive relationship in which a table exists a foreign key column that references its own primary key. In the project, the most common one-to-many reflexive relationship is the classification table, and the classification table holds the reference primary key through a parentid column, and an infinite level of recursion has been implemented.

Fluent API Implementation Method:

File class Category.cs:

Using system;using system.collections.generic;namespace portal.entities{public    class Category    {        public int CategoryID {get; set;}        public int Categoryno {get; set;}        public string CategoryName {get; set;}        Public nullable<int> ParentID {get; set;}        Public virtual Category Parent {get; set;}        Public virtual icollection<category> Children {get; set;}}    }

Map File class CategoryMap.cs:

Using system.componentmodel.dataannotations.schema;using system.data.entity.modelconfiguration;using        Portal.entities;namespace portal.mapping{public class Categorymap:entitytypeconfiguration<category> { Public Categorymap () {//Primary Key this.            Haskey (t = T.categoryid); Properties this. Property (t = t.categoryname). IsRequired ().            Hasmaxlength (50); Table & Column Mappings this.            ToTable ("Category"); This. Property (t = T.categoryid).            Hascolumnname ("CategoryID"); This. Property (t = T.categoryno).            Hascolumnname ("Categoryno"); This. Property (t = t.categoryname).            Hascolumnname ("CategoryName"); This. Property (t = T.parentid).            Hascolumnname ("ParentID"); Relationships this. Hasoptional (t = t.parent). Withmany (t = t.children). Hasforeignkey (d =&Gt        D.parentid); }    }}

After the above code is run, the resulting data table:

  6. Many-to-many reflexive relationships

Example of a many-to-many relationship: A record in family may have more than one parents, or there may be more than one children.

File class Family.cs:

View Code

Map File class FamilyMap.cs:

View Code

Family class and map configuration class, the data table structure that is generated after running:

In the table structure above, specifies that the mediation table between family is Familyrelationship, where Familyrelationship's two fields ParentID and childID refer to Familyi in the FamilyID table as foreign keys. It may be uncommon to have this many-to-many reflexive reference relationships in the actual project process.

Http://www.cnblogs.com/libingql/p/3353112.html

Entity Framework Code First Relational Mapping Convention "L Forwarding"

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.