asp.net mvc - Should I follow specific naming pattern for my foreign key, if I want to map my database tables using ado.net Entity Framework? -
i reading next tutorial regarding entity framework uses code-first approach link
and mentioned ef interpret fks, between these 2 classes, need utilize next 2 naming patterns or rules:-
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 of study course { get; set; } public virtual pupil student { get; set; } } public class pupil { 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; } }
then entity framework interprets property foreign key property:
rule1 if it's named <navigation property name><primary key property name>
(for example, studentid
student
navigation property since pupil entity's primary key id).
rule2 foreign key properties can named same <primary key property name>
(for example, courseid
since course of study entity's primary key courseid
).
but if have database , not next naming pattern problem? illustration allow define student-->enrollment
relation follow within sql server enrollment.studentno ---> student.studentid
, define field called studentno
fk student.studentid
(i did testing purposes), cause problem? own test noted ef happily mapping enrollment.studentno
student.studentid
(even can define fk named "nonamepetten
"),, above 2 rules valid when using code-first approach , not need follow them if using db-first approach ?
thanks
if you're using database-first, , relationship exists in sql database, should fine. ef smart plenty mapping in generated context code.
if you're using code-first, don't need follow convention. can phone call relevant fields whatever heart desires, need tell ef relationship between them. can in 1 of 2 ways: fluent api in dbcontext class, or info annotations in entity class (my personal favorite).
to you're asking, next in enrollment
class:
public int enrollmentid { get; set; } [foreignkey("student")] public int studentno { get; set; } public virtual pupil student { get; set; }
asp.net-mvc entity-framework ado.net asp.net-mvc-5
No comments:
Post a Comment