I want to implement One to One relation with both ends required with the fluent API in Entity Framework 6 code first.
I have the principal class:
public class Student
{
public int Id{ get; set;}
public string Name{ get; set;}
public StudentProfile StudentProfile { get; set; }
}
and I have the dependent class:
public class StudentProfile
{
public int Id{ get; set;}
public string Description{ get; set;}
public Student Student { get; set; }
}
Additionally, I have the configuration for the relation one to one, in this case both ends ARE REQUIRED:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasRequired(student => student.StudentProfile)
.WithRequiredPrincipal(profile => profile.Student);
base.OnModelCreating(modelBuilder);
}
After executing update-database, the resulting generated tables are:
The table StudentProfile columns:
The table Students columns:
On the Main program, I am able to save a Student with its profile:
UMLModel umlContext = new UMLModel();
//Studentprofile object
StudentProfile studentProfile = new StudentProfile();
studentProfile.Description = "Emily Profile Description";
//Student object
Student student = new Student();
student.Name = "Emily";
student.StudentProfile = studentProfile;
//Save Student and StudenProfile Objects
umlContext.Students.Add(student);
umlContext.SaveChanges();
Once executed the Main program,on the database,the StudentProfiles table is:
and the Students table is:
The problem becomes when I try to save one student WITHOUT its profile, the program allows to save it and it is supposed to not allow it:
UMLModel umlContext = new UMLModel();
Student student = new Student();
student.Name = "John";
umlContext.Students.Add(student);
umlContext.SaveChanges();
After executing the Main program, on the database, for table StudentProfiles now is:
and for table Students:
One way to prevent this is using data annotations, but I don't like this approach due the domain classes needs additional code:
public class Student
{
public int Id{ get; set;}
public string Name{ get; set;}
[Required]
public virtual StudentProfile StudentProfile { get; set; }
}
Questions:
Thanks in advance!
Perhaps have a look at the Stack Overflow answer here, which gives a nice explanation about 1:1 mappings in Entity Framework and some options for how you can map them so both ends are required: https://stackoverflow.com/a/30516623/2128831