我无法让与 EF 的一对一关系正常工作。我为博客、SO 和 msdn 文档评分,但我所做的一切似乎都不起作用。
我有两个模型,一个类和一个考试,如下所示:
[Table("classes")]
public class Class
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[StringLength(255), Required]
public string Title { get; set; }
public virtual Exam Exam { get; set; }
}
[Table("exams")]
public class Exam
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[DisplayFormat(DataFormatString = "{0:h:mm tt}")]
public DateTime? Time { get; set; }
public int ClassId { get; set; }
public virtual Class Class { get; set; }
}
我希望能够从课堂和考试中访问考试,但无论我做什么,我都会发现一些错误。
尝试创建/运行迁移我得到以下信息。
The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
如果我将此添加到我的上下文中:
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Entity<Exam>()
.HasRequired(e => e.Class)
.WithOptional(c => c.Exam);
}
我收到以下错误:
System.Data.Entity.Infrastructure.DbUpdateException: Entities in 'BenchContext.Exams' participate in the 'Class_Exam' relationship. 0 related 'Class_Exam_Source' were found. 1 'Class_Exam_Source' is expected. ---> System.Data.UpdateException: Entities in 'BenchContext.Exams' participate in the 'Class_Exam' relationship. 0 related 'Class_Exam_Source' were found. 1 'Class_Exam_Source' is expected.
我不确定如何告诉流利的 api 如何正确地在两个模型之间使用外键,而我所做的任何事情似乎都不会影响它。
我错过了什么?