1

I am implementing one to one relationship in entity framework using code first approach. Below are my models.

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }

    public virtual Caption Caption { get; set; }

}

and this one

public class Caption
{

    public int CaptionId { get; set; }
    public string CaptionDesc { get; set; }
    public virtual Course Course { get; set; }
}

and in context I have used following code

modelBuilder.Entity<Course>().HasRequired(c => c.Caption).WithRequiredPrincipal(c => c.Course);

while reading this article here, One to One Relationship Example, They said that when let's say you are saving course entity without caption so exception will be thrown and entity framework won't let you store the entity. But When I did, I didn't got any exception. I can store both entities without any dependency. Please tell me what I am doing wrong. I am using entity framework 6

Edit: The tables looks as following. enter image description here

Jamal Hussain
  • 391
  • 1
  • 3
  • 13
  • You haven't put any `Primary Keys` or `Foreign Keys` on either table showing their constraints. How do the tables look in `SQL Server SSMS`? – SS_DBA May 15 '17 at 17:47
  • He doesn't need to. Courseid and CaptionId follow convention so EF is smart enough to tell. – Steve Greene May 15 '17 at 17:49
  • That's what I thought, but if he's inserting rows without `Caption`, then shouldn't he explicitly enforce the relationships with `Key` and `Foreign Key`? – SS_DBA May 15 '17 at 17:52
  • Technically you can't do 1:1 in SQL Server. See [here](http://stackoverflow.com/questions/10292355/how-do-i-create-a-real-one-to-one-relationship-in-sql-server). The usual approach is described in your link: Add CourseId (and remove CaptionId) to the Caption table and make CourseId BOTH the primary key and foreign key. – Steve Greene May 15 '17 at 17:57

1 Answers1

0

1:1 relationships in entity framework are only supported when the tables share a primary key. Check out this article for help understanding: http://blog.bennymichielsen.be/2011/06/02/entity-framework-4-1-one-to-one-mapping/

Travis Acton
  • 4,292
  • 2
  • 18
  • 30