Search code examples
.netentity-frameworkef-code-firstone-to-many

What difference One-to-Many Relationships in Code-First?


I try all of them but results are quiet same.Did all do the same thing?

I can simple add the first one why should I use other ones?

Here is the code I looked;

 //1-One to Many  
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public Grade Grade { get; set; }
}

public class Grade
{
public int GradeId { get; set; }
public string GradeName { get; set; }
public string Section { get; set; }
}

The second is:

      //second...
 public class Student
  {
    public int StudentId { get; set; }
    public string StudentName { get; set; }
   }

public class Grade
{
public int GradeId { get; set; }
public string GradeName { get; set; }
public string Section { get; set; }

public ICollection<Student> Students { get; set; } 
}

The third:

       //third...
       public class Student
     {
     public int Id { get; set; }
     public string Name { get; set; }
     public Grade Grade { get; set; }
    }



 public class Grade
{
   public int GradeID { get; set; }
   public string GradeName { get; set; }
   public string Section { get; set; }

   public ICollection<Student> Student { get; set; }
}

And last:

        //fourth..
        public class Student
   {
      public int Id { get; set; }
      public string Name { get; set; }

      public int GradeId { get; set; }
      public Grade Grade { get; set; }
      }


  public class Grade
 {

public int GradeId { get; set; }
public string GradeName { get; set; }

public ICollection<Student> Student { get; set; }
}

Here is a link where I looked the code:

http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx


Solution

  • Yes, you are right all are same But different ways to define the same relationship.

    You can refer https://learn.microsoft.com/en-us/ef/core/modeling/relationships for better understanding.