2

我的模型如下:

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 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; }

}

这里是三等。同上,需要一对一关系外键。

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; }
}

我收到以下错误。

在模型生成过程中检测到一个或多个验证错误:\tSystem.Data.Entity.Edm.EdmAssociationEnd: : 多重性在关系“Form2_Form1”中的角色“Form2_Form1_Source”中无效。因为从属角色属性不是关键属性,所以从属角色的多重性的上限必须是' '。*

我在这里做错了什么?

看来我被这件事打动了。!!也许数据库优先方法更好。

4

1 回答 1

3

对于一对一关系,EF 期望表使用相同的主键。真的,如果这是真正的一对一,他们可能应该这样做。因此,在您的示例中,如果您将 ID 作为 Form2 和 Form3 表的主键,那么您的一对一将起作用。

 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; }
}
于 2014-08-11T10:36:43.263 回答