Norman Bentley
Norman Bentley

Reputation: 660

EF Code first 1 to 1 relationship error

I have two classes:

Main class:

public class CCourseDetailModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CourseDetailId { get; set; }

    [ForeignKey("CourseOutcomes")]
    public int CourseOutcomesId { get; set; }

    public virtual CACourseOutcomesModel CourseOutcomes { get; set; }
}

Dependent class:

public class CACourseOutcomesModel
{
    [Key, ForeignKey("CourseDetail")]
    public int CourseOutcomesId { get; set; }

    [Required]
    public virtual CCourseDetailModel CourseDetail { get; set; }
}

I have 10 or so similar classes, with 1 to 1 relationships that work fine. This is the only one giving me the following error:

CACourseOutcomesModel_CourseDetail_Target: : Multiplicity is not valid in Role 'CACourseOutcomesModel_CourseDetail_Target' in relationship 'CACourseOutcomesModel_CourseDetail'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be ''.*

Any idea where I'm going wrong? Need a fresh set of eyes please. Thanks!

Upvotes: 3

Views: 2132

Answers (1)

ocuenca
ocuenca

Reputation: 39326

In a one to one relationship, one end must be principal and the another one must be dependent, so you can't have a FK property in both sides. Remove the FK property in the principal (CCourseDetailModel) and in CACourseOutcomesModel you don't need to use Required attribute. Using ForeignKey attribute you already are telling to EF who is the dependent end.

In Fluent Api would be:

modelBuilder.Entity<CACourseOutcomesModel>()
            .HasRequired(p => p.CourseDetail)
            .WithOptional(p => p.CourseOutcomes);

So your model should be this way:

public class CCourseDetailModel
{
    [Key]
    //[DatabaseGenerated(DatabaseGeneratedOption.Identity)] don't need this, it's the configuration by default.
    public int CourseDetailId { get; set; }

    public virtual CACourseOutcomesModel CourseOutcomes { get; set; }
}

public class CACourseOutcomesModel
{
    [Key, ForeignKey("CourseDetail")]
    public int CourseOutcomesId { get; set; }

    public virtual CCourseDetailModel CourseDetail { get; set; }
}

Upvotes: 4

Related Questions