locked
Entity Framework 1-to-1 relationship is not throwing an exception when save changes is called RRS feed

  • Question

  • I'm trying to do a 1-to-1 mapping in Entity Framework and one example I found online was: http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx (see Configure One-to-One relationship using Fluent API section)..as well in some books that I've read while trying to implement this.

    Here are my entities:

    public class Student
    {
        public Student() { }
    
        public int StudentId { get; set; }
        public string StudentName { get; set; }
    
        public virtual StudentAddress Address { get; set; }
    
    }
    public class StudentAddress
    {
        public int StudentId { get; set; }
    
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public int Zipcode { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
    
        public virtual Student Student { get; set; }
    }

    My data context that includes configuration using the fluent api:

    public class DataContext : DbContext
    {
        public DbSet<Student> Student { get; set; }
    
        // public DbSet<StudentAddress> Addresses { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Configure StudentId as PK for StudentAddress
            modelBuilder.Entity<StudentAddress>()
                .HasKey(e => e.StudentId);
    
            // Configure StudentId as FK for StudentAddress
            modelBuilder.Entity<Student>()
                        .HasRequired(s => s.Address)
                        .WithRequiredPrincipal(ad => ad.Student);
    
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new DataContext())
            {
                var student = new Student { StudentName = "sample name" };
                context.Student.Add(student);
                context.SaveChanges();
            }
                Console.ReadKey();
        }
    }

    In the console application, I expect it throw an exception since a Student must have a StudentAddress in order for it be saved, but when I ran the application and checked the database the student entry actually got saved. I might be missing something under the hood...though if I try adding the [Required] attribute on top of the StudentAddress property of the Student class, it throws an exception If I don't supply a StudentAddress for a Student Entity.

    Your feedback/help would be of great help and be very much appreciated. Thanks!


    Saturday, July 23, 2016 6:29 AM

Answers

  • >I might be missing something under the hood

    Yes.  It's really not workable on the relational side to have that kind of relationship.  EG

    create table A
    (
      ID int primary key,
      BID int not null
    )
    
    create table B
    (
      ID int primary key,
      AID int not null references A
    )
    
    alter table A 
    add constraint fk_B 
    foreign key (BID) references B(ID)
    

    In SQL Server you would never be able to insert a row, as the constraints are checked during the inserts. 

    So while EF allows you to declare that in the object model, it doesn't enforce it in the database. 

    David


    David http://blogs.msdn.com/b/dbrowne/


    Monday, July 25, 2016 1:44 PM

All replies

  • Hi randelramirez,

    Thanks for posting here.

    Based on your description and related code snippet, I create a demo and reproduce your issue on my side, it seems that entity framework does not work with one-to-one relationship. I have post your issue on Microsoft feedback. 

    https://connect.microsoft.com/VisualStudio/feedback/details/2972224

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, July 25, 2016 2:35 AM
  • >I might be missing something under the hood

    Yes.  It's really not workable on the relational side to have that kind of relationship.  EG

    create table A
    (
      ID int primary key,
      BID int not null
    )
    
    create table B
    (
      ID int primary key,
      AID int not null references A
    )
    
    alter table A 
    add constraint fk_B 
    foreign key (BID) references B(ID)
    

    In SQL Server you would never be able to insert a row, as the constraints are checked during the inserts. 

    So while EF allows you to declare that in the object model, it doesn't enforce it in the database. 

    David


    David http://blogs.msdn.com/b/dbrowne/


    Monday, July 25, 2016 1:44 PM