Note that there are some explanatory texts on larger screens.

plurals
  1. POmake both models aware of each other with a one-to-one relationship in asp.net entity framework
    primarykey
    data
    text
    <p>I am unable to get the one to one relationship with EF to work properly. I've scored blogs, SO, and msdn docs, but nothing I do seems to work. </p> <p>I have two models, a Class and an Exam that look like the following:</p> <pre><code>[Table("classes")] public class Class { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [StringLength(255), Required] public string Title { get; set; } public virtual Exam Exam { get; set; } } [Table("exams")] public class Exam { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [DisplayFormat(DataFormatString = "{0:h:mm tt}")] public DateTime? Time { get; set; } public int ClassId { get; set; } public virtual Class Class { get; set; } } </code></pre> <p>I want to be able to access the exam from the Class and the Class from the Exam, but no matter what I do, I find some error.</p> <p>Trying to create/run migrations I get the following.</p> <pre><code>The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations. </code></pre> <p>If I add this to my context:</p> <pre><code>protected override void OnModelCreating(DbModelBuilder builder) { builder.Entity&lt;Exam&gt;() .HasRequired(e =&gt; e.Class) .WithOptional(c =&gt; c.Exam); } </code></pre> <p>I get the following error:</p> <pre><code>System.Data.Entity.Infrastructure.DbUpdateException: Entities in 'BenchContext.Exams' participate in the 'Class_Exam' relationship. 0 related 'Class_Exam_Source' were found. 1 'Class_Exam_Source' is expected. ---&gt; System.Data.UpdateException: Entities in 'BenchContext.Exams' participate in the 'Class_Exam' relationship. 0 related 'Class_Exam_Source' were found. 1 'Class_Exam_Source' is expected. </code></pre> <p>I'm not sure how to tell the fluent api how to correctly foreign key between the two models and nothing I do seems to affect it.</p> <p>What am I missing?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload