简体   繁体   中英

Foreign Key in Entity Framework

I am reading through this tutorial.... ASP.NET Code First MVC Tutorial

In this example, Student Class has the "ID" property.

Enrollment Class has "StudentID" property.

Now, If all the additional definition in Enrollment class says,

                public virtual Student Student { get; set; }

Just by that statement, will the EF know that StudentID is foreign key?

My confusion is, in the Student Table, property name is "ID" .. Say in the Enrollment Class, instead of StudentID, I call it.... Student_ID....will the EF still correlate Student.ID as the same as Enrollment.Student_ID and establish foreign key? Does it just need the "Student" string in a property name in Enrollment class to establish relationship?

Code snippets from the site...

       using System;
       using System.Collections.Generic;

       namespace ContosoUniversity.Models
       {
           public class Student
           {
               public int ID { get; set; }
               public string LastName { get; set; }
               public string FirstMidName { get; set; }
               public DateTime EnrollmentDate { get; set; }

               public virtual ICollection<Enrollment> Enrollments { get; set; }
           }
       }



       namespace ContosoUniversity.Models
       {
           public enum Grade
           {
               A, B, C, D, F
           }

           public class Enrollment
           {
               public int EnrollmentID { get; set; }
               public int CourseID { get; set; }
               public int StudentID { get; set; }
               public Grade? Grade { get; set; }

               public virtual Course Course { get; set; }
               public virtual Student Student { get; set; }
           }
       }

Entity Framework follows a "Convention over configuration" approach with regards to Foreign Keys.

"Any property with the same data type as the principal primary key property and with a name that follows one of the following formats represents a foreign key for the relationship: '[navigation property name][principal primary key property name]', '[principal class name][primary key property name]', or '[principal primary key property name]'. If multiple matches are found then precedence is given in the order listed above. Foreign key detection is not case sensitive. "

Source: http://msdn.microsoft.com/en-us/data/jj679962.aspx

So as long as you follow one of the conventions then it will infer the Foreign Key for you. If you don't follow one of the conventions, then you will have to explicitly state the relationship through a configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM