Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I define `foreign key Id` property in addition to the corresponding `navigation property`?

I found these entities in one of Microsoft tutorials:

public class Enrollment
{
    public int Id{ get; set; }

    public int StudentId { get; set; }
    public Student Student { get; set; }
}

public class Student
{
    public int Id { get; set; }

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

Do I really need to define StudentId property?

How the case will differ in case of different types of relationshipts? for example one-one and one-many?

UPDATE:

In this link http://www.learnentityframeworkcore.com/relationships we can see that in One-Many and Many-Many, they did not define the Id foreign key property, but in One-One, they did. Why is that?

like image 748
Mohammed Noureldin Avatar asked Nov 03 '17 00:11

Mohammed Noureldin


1 Answers

I found a partial answer for my question in this page:

http://www.learnentityframeworkcore.com/conventions

Foreign Key Shadow Properties:
If you choose not to explicitly include a foreign key property in the dependant end of the relationship, EF Core will create a shadow property using the pattern Id.

But I still do not know if this is the case in all types of relationships.

I hope that helps some one.

UPDATE

Ok now I found exactly what I wanted to know and understand, please take a look on these links which include the difference conventions of creating the Models (entities):

http://www.learnentityframeworkcore.com/conventions/one-to-many-relationship

http://www.learnentityframeworkcore.com/conventions/one-to-one-relationship

like image 125
Mohammed Noureldin Avatar answered Sep 28 '22 01:09

Mohammed Noureldin