首先,我看到Implementing Zero Or One to Zero Or One relationship in EF Code first by Fluent API。
我想在我的MVC 4项目中实现0..1(学生):0..1(GraduationWork)。
我有POCO课程:
public class GraduationWork
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int GraduationWorkID { get; set; }
[Display(Name = "Student")]
public int? StudentID { get; set; }
[ForeignKey("StudentID")]
public virtual Student Student { get; set; }
....
}
和
public class Student : UserProfile
{
[Required]
public int? GraduationWorkID { get; set; }
[ForeignKey("GraduationWorkID")]
public virtual GraduationWork GraduationWork { get; set; }
....
}
我的部分OnModelCreating:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().HasOptional(x => x.GraduationWork)
.WithOptionalPrincipal(s => s.Student)
.Map(x => x.MapKey("StudentID"));
modelBuilder.Entity<GraduationWork>().HasOptional(x => x.Student)
.WithOptionalPrincipal(g => g.GraduationWork)
.Map(x => x.MapKey("GraduationWorkID"));
}
我想也许继承存在问题,但我不知道......你会这么善良并帮助我吗? :)
答案 0 :(得分:1)
根据此Link
您可以通过两种方式创建0.1 --- 0.1映射。
**************************************使用属性******* *************
public class Student : UserProfile
{
public int StudentId { get; set; }
public virtual GraduationWork GraduationWork { get; set; }
}
public class GraduationWork
{
[Key]
[ForeignKey("Student")]
public int StudentID { get; set; }
public virtual Student Student { get; set; }
}
注意:学生和GraduationWork实体之间存在一对一或一对一的关系。毕业作业仅与其分配的学生相关,因此其主键也是其实体的外键。但实体框架无法自动将StudentID识别为GraduationWork Entity中的主键,因为其名称不遵循ID或classnameID命名约定。因此,Key属性用于将其标识为键:
[Key]
[ForeignKey("Student")]
public int StudentID { get; set; }
*******************************使用流利的Api ************* **********
以下代码提供了一个示例,说明如何使用流畅的API而不是属性来指定Student和GraduationWork实体之间的关系:
modelBuilder.Entity<Student>()
.HasOptional(p => p.GraduationWork ).WithRequired(p => p.Student);
了解更多信息