C# 代码优先外键-多重性在角色中无效
我的型号如下:C# 代码优先外键-多重性在角色中无效,c#,entity-framework,ef-code-first,ef-fluent-api,C#,Entity Framework,Ef Code First,Ef Fluent Api,我的型号如下: 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; } [Displa
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.edmsociationEnd::多重性在关系“Form2\u Form1”中的角色“Form2\u Form1\u Source”中无效。因为从属角色属性不是键属性,所以从属角色的多重性上限必须为“”*
我在这里做错了什么
看来我被这件事深深打动了。!!也许数据库优先的方法更好。对于一对一关系,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; }
}
它不起作用:EntityFramework.dll中发生类型为“System.InvalidOperationException”的异常,但未在用户代码中处理其他信息:无法确定类型“RecipeForm.Models.Form2”和“RecipeForm.Models.Form1”之间关联的主端。必须使用关系fluent API或数据注释显式配置此关联的主体端。