EntityFramework Code-first Easy Tutorial (ix)-------one-to-many

Source: Internet
Author: User

One-to-many (One-to-many) relationships:

Here, let's introduce a one-to-many relationship with Code-first, for example, include multiple student classes in a standard (grade) class.

For more information on One-to-one,one-to-many,many-to-many relationships, please visit the Entity relationship

To configure One-to-many relationships using DataAnnotations:

As shown in the following code:

 Public classstudent{ PublicStudent () {} Public intStudentID {Get;Set; }  Public stringStudentname {Get;Set; }  Public VirtualStandard Standard {Get;Set; }}  Public classstandard{ PublicStandard () {Students=NewList<student>(); }     Public intStandardid {Get;Set; }  Public stringDescription {Get;Set; }  Public VirtualIcollection<student> Students {Get;Set; }}

As shown in the code above, the student entity class contains the Navigation property standard, and the standard entity class contains the collection attribute student, which is the default one-to-many relationship.

If the entity class follows such a default convention, it is a one-to-many relationship by default, and we do not need the additional configuration of dataannotations or the fluent API.

In the database, Code-first creates a one-to-many relationship by adding a Standard_standardid foreign key column to the student table.

We recommend that you include a foreign key attribute in an entity class, such as the above code, if you create the Standardid property in the student entity class, it will automatically become a foreign key because it follows the default convention that the foreign key format should be the format of the < type name >id.

Similarly, if we create a foreign key property name that does not follow the default naming convention, then we need to manually add the attribute, as shown in the following code, the Student class contains a Standardrefid property:

 Public classstudent{ PublicStudent () {} Public intStudentID {Get;Set; }  Public stringStudentname {Get;Set; }  Public intStandardrefid {Get;Set; } [ForeignKey ("Standardrefid")]     Public VirtualStandard Standard {Get;Set; }}  Public classstandard{ PublicStandard () {studentslist=NewList<student>(); }     Public intStandardid {Get;Set; }  Public stringDescription {Get;Set; }  Public VirtualIcollection<student> Students {Get;Set; }}

If the code, we must add the standard property to the [ForeignKey ("Standardrefid")] feature, so that when creating the database will be Standardrefid set as a foreign key, the database as follows:

Configure the One-to-many relationship using the Fluent API:

Or take the example of the above two classes

The student class and standard class codes are as follows:

 Public classstudent{ PublicStudent () {} Public intStudentID {Get;Set; }  Public stringStudentname {Get;Set; }  Public intStandardid {Get;Set; }  Public VirtualStandard Standard {Get;Set; }}  Public classstandard{ PublicStandard () {studentslist=NewList<student>(); }     Public intStandardid {Get;Set; }  Public stringDescription {Get;Set; }  Public VirtualIcollection<student> Students {Get;Set; }}

Use the fluent API to configure a one-to-many relationship code:

protected Override void onmodelcreating (Dbmodelbuilder modelBuilder) {        //        modelbuilder.entity< Student>()                    . hasrequired////Standard                      entity includes many Students entities }

This is when foreign key naming for the default two classes follows the convention naming case, if the student class contains a foreign key name that does not follow the Convention, as follows:

 Public classstudent{ PublicStudent () {} Public intStudentID {Get;Set; }  Public stringStudentname {Get;Set; } //stdID has a name that differs from the Code-first default contract naming     Public intStdId {Get;Set; }  Public VirtualStandard Standard {Get;Set; }}  Public classstandard{ PublicStandard () {studentslist=NewList<student>(); }     Public intStandardid {Get;Set; }  Public stringDescription {Get;Set; }  Public VirtualIcollection<student> Students {Get;Set; }}

As shown above, stdID does not follow the foreign key naming convention for the default < type name >id, so our fluent API is configured as follows:

protected Override void onmodelcreating (Dbmodelbuilder modelBuilder) {        //        modelbuilder.entity< Student>()                    . Hasrequired<Standard> (s = s.standard)                    ( s.students)                    = s.stdid);}

As you can see, the standard modelBuilder.Entity<Student>().HasRequired<Standard>(s => s.Standard) attribute of a specially specified student entity cannot be empty, the standard .WithMany(s => s.Students).HasForeignKey(s => s.StdId) entity is specified to contain multiple student entities, and the foreign key is stdID.

Note: Each generic method returns an object of that type, so it is possible to have such a string of ^_^)

So for the above configuration code, we can also write the configuration code at the beginning of the standard class, as follows:

protected Override void onmodelcreating (Dbmodelbuilder modelBuilder) {        //Configure One-to-many        Modelbuilder.entity<standard>()                    . Hasmany//standard hasmany Students                    . Withrequired (s = s.standard)  //Student requireone standard                    . Hasforeignkey (s = = S.stdid); // Student includes specified ForeignKey property nameto Standard}

After the code is run, the following database is created:

Note that stdID is not an empty column, so you must specify the standard property of the student entity class each time you join and update the students table.

To configure a nullable foreign key in a one-to-many relationship:

It is simple to use the Hasoptional method instead of the Hasrequired method.

protected Override void onmodelcreating (Dbmodelbuilder modelBuilder) {        //        modelbuilder.entity< Student>()                    . Hasoptional<Standard> (s = s.standard)                    ( s.students)                    =  S.stdid);}

This way, the stdID column of the students table can be empty.

Recently too busy, work, life, in short, sometime bar, since the determination to go further, you can not promise. Come here today, the next chapter will talk about the operation of many-to-many relationships.

EntityFramework Code-first Easy Tutorial (ix)-------one-to-many

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.