2
votes

My Model as below:

public class Form1
{
    [Key]
    public long Id { get; set; }

    [Required]
    [Display(Name = "Name")]
    public string Name { get; set; }

    [Required]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Display(Name = "Department", Prompt = "Please enter your department")]
    public string Department { get; set; }


    public  Form1 Form1{ get; set; }
    public  Form2 Form2 { get; set; }
}

Second Class (Need one to one relationship) so setting Foreign key

public class Form2
{
    [Key]
    public long Form2_ID { get; set; }

    [ForeignKey("Form1")]
    public long Id { get; set; }


    //Mobile Home Page
    public string Location1 { get; set; }
    [DataType(DataType.MultilineText)] 

    //[ForeignKey("Id")]  //Even this is not working
    public  Form1 Form1 { get; set; }

}

Third class here. Same as above and needed One to One relationship Foreign Key.

public class Form3
{
    [Key]
    public long Form3_ID { get; set; }

    [ForeignKey("Form1")]
    public long Id { get; set; }

    [Display(Name = "Rhombus")]
    public bool Rhombus { get; set; }


    public  Form1 Form1 { get; set; }
}

I am getting following error.

One or more validation errors were detected during model generation: \tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'Form2_Form1_Source' in relationship 'Form2_Form1'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be ''.*

What wrong I am doing here?

Looks like I am struck up in this.!! Maybe Database first approach is better.

1

1 Answers

3
votes

For one-to-one relationships, EF expects that the tables are using the same primary key. And really, if it's a true one-to-one they probably should. So in your example, if you make ID the primary key on the Form2 and Form3 table, your one-to-one will work.

 public class Form1
 {
    [Key]
    public long Id { get; set; }

    [Required]
    [Display(Name = "Name")]
    public string Name { get; set; }

    [Required]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Display(Name = "Department", Prompt = "Please enter your department")]
    public string Department { get; set; }       

   public  Form1 Form1{ get; set; }
   public  Form2 Form2 { get; set; }

}

   public class Form2
{
    [Key]
    public long Id { get; set; }


    //Mobile Home Page
    public string Location1 { get; set; }
    [DataType(DataType.MultilineText)] 

    public  Form1 Form1Obj { get; set; }

}

public class Form3
{
    [Key]
    public long Id { get; set; }

    [Display(Name = "Rhombus")]
    public bool Rhombus { get; set; }


    public  Form2 Form2Obj { get; set; }
}