4

I have these entities:

 public class StudentBag
 {
    public int BagIdentifier { get; set; }
    public Student Student { get; set; }
 }

 public class Student
 {
    public string Name { get; set; }
    public StudentBag StudentBag{get;set;}

 }

I want to configure a one to one relationship. my question is if there is a difference between:

modelBuilder.Entity<StudentBag>()
            .HasRequired(t => t.Student)
            .WithRequiredDependent(t=>t.StudentBag);

        modelBuilder.Entity<StudentBag>()
            .HasRequired(t => t.Student)
            .WithRequiredPrincipal(t => t.StudentBag);

and I will appreciate if someone will explain what it is mean principle and dependent...

Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
ilay zeidman
  • 2,654
  • 5
  • 23
  • 45
  • 1
    Look at http://stackoverflow.com/questions/6531671/what-does-principal-end-of-an-association-means-in-11-relationship-in-entity-fr – Michał Krzemiński Jun 05 '14 at 06:46
  • 1
    I looked it talk about one to one or zero relationship no? "Principal end is the one which will be inserted first and which can exist without the dependent one" so I dont understand why in one to one I need it? In my example student can't exist without studendBag... – ilay zeidman Jun 05 '14 at 06:57
  • But entity framework still needs to put principal id into dependents foreign key column. Main difference between them, is that dependent has column with foreign key in it. – Michał Krzemiński Jun 05 '14 at 07:02
  • 1 to 1 is an anomaly. Both objets must be created together, updated together and deleted together. What's the point for this relation? What is your use case? Perhaps you need to use `ComplexObject`. – JotaBe Jun 05 '14 at 14:52

1 Answers1

7

It's pretty simple, the class that has the navigation property to the foreign class is the Principal.

When the required class has the reference to the main class you should use: WithRequiredPrincipal()

When the required class is referenced by the main class you should use: WithRequiredDependent()

Eg. That way the two maps below are the same.

    //modelBuilder.Entity<>(Student)
        //.HasRequired(t => t.StudentBag)
        //.WithRequiredDependent();

    modelBuilder.Entity<Student>()
        .HasRequired(t => t.StudentBag)
        .WithRequiredDependent();

    modelBuilder.Entity<StudentBag>()
        .HasRequired(t => t.Student)
        .WithRequiredPrincipal();
XPD
  • 1,121
  • 1
  • 13
  • 26
Rodolfo Leal
  • 527
  • 5
  • 15